我不知道为什么在我的 fragment 中调用 getView 时它返回 NULL。
我知道我可以在 onCreateView 方法
执行后调用 getView
我调试了我的应用程序:我检查了首先调用的是 onCreateView 方法。
所以我不知道问题出在哪里。
我给你看我的代码:
这是我的主要 Activity ,当用户点击抽屉菜单时,我会检查按下菜单的哪个声音:
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,所以在这个 block 中我创建了一个新的
fragment ,使用静态方法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;
}
之后,我只需将 fragment 交给方法:replace。
它有效,我还可以看到他调用了 CreaVotoFragment 类中覆盖的 onCreateView 方法。
当我调用 createMark 方法(if block 的最后一行)时,问题就开始了。
在 createMark 方法内部,当我调用 getView 时,返回一个空指针。
最佳答案
您应该注意到 commit()
将在 Handler.post()
上运行。这意味着您的 fragment View 将在 onNavigationDrawerItemSelected
之后创建。
如果您从 fragment 内部调用 View 相关方法来约束 View 的生命周期,效果会更好。
关于android - fragment - getView() 方法返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024863/