1

我不知道为什么在我调用 getView 时在我的片段中它返回 NULL。

我知道我可以在我调试我的应用程序的onCreateView 方法执行后调用 getView :我检查了第一个被称为 onCreateView 方法。 所以我不知道问题出在哪里。 我向您展示我的代码: 这是我的主要活动,当用户单击抽屉菜单时,我检查按下了菜单的哪个声音:





public void onNavigationDrawerItemSelected(int position) {
     ...    
     if (position == 7) {
                CreaVotoFragment fragment = CreaVotoFragment.newInstance(position + 1);
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, fragment)
                        .commit();
                //Mostra un Dialog che consente l'eliminazione di un corso
                fragment.createMark(this);
     }
     ...
 }

在这种情况下,用户按下了 7 号语音菜单,所以在这个块中,我使用静态方法 newIstance 创建了一个新片段。

这是方法:

public static CreaVotoFragment newInstance(int sectionNumber) {
    CreaVotoFragment fragment = new CreaVotoFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
}

之后,我只是将片段提供给方法:替换。

它工作,我还可以看到他调用了 CreaVotoFragment 类中覆盖的 onCreateView 方法。

当我使用 createMark 方法(if 块的最后一行)调用时,问题就开始了。
在 createMark 方法内部,当我调用 getView 时,返回一个空指针。

4

1 回答 1

2

您应该注意到commit()将在Handler.post(). 这意味着您的片段视图将在 AFTER 之后创建onNavigationDrawerItemSelected

如果你从片段内部调用视图相关的方法来约束视图的生命周期,那就更好了。

于 2014-11-19T21:08:40.683 回答