我将滑块菜单displayview方法设为:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
FragmentManager fm = getSupportFragmentManager();
String tag = fragment.getTag(); // instance method of a to get a tag
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
setTitle(navMenuTitles[position]);
drawer.closeDrawer(drawerListView);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
我有一个名为home_fragment的片段,其后面的代码是HomeFragment.java
当我点击这个片段时,它首先工作正常,但是在索引0的侧板菜单上单击下一步时出现错误:
Attempt to write to field 'int android.support.v4.app.Fragment.mNextAnim' on a null object reference
我做错了什么?感谢。
这是我遇到错误的地方:
case OP_REMOVE: {
Fragment f = op.fragment;
f.mNextAnim = exitAnim;
mManager.removeFragment(f, transition, transitionStyle);
} break;
此代码存在于BackStackRecord.java
中答案 0 :(得分:1)
你不应该打电话给container.removeAllViewsInLayout()
。
FragmentManager
将在您调用FragmentTransaction.replace()
时处理容器上的所有视图操作,包括删除当前片段视图。您可能会收到错误,因为FragmentManager
希望片段的视图位于容器中,但您已将其删除。
所有你需要的是:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
// set fragment to other nav target
fragment = ...
break;
.
.
.
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
setTitle(navMenuTitles[position]);
drawer.closeDrawer(drawerListView);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
此外,我注意到您正在使用getFragmentManager()
。请检查您的课程输入,并确保您有正确的电话。
HomeFragment
延伸android.app.Fragment
,请使用getFragmentManager()
。HomeFragment
延伸android.support.v4.app.Fragment
,请使用getSupportFragmentManager()
。