我有一个Navigation Drawer
,它有5个项目。如果用户选择一个项目,我将在FrameLayout
中加载相应的Fragment
现在,如果用户拉出Navigation Drawer
并选择与以前相同的项目,我不应该再次加载相同的Fragment
,所以我保存所选的位置,如果以前选择的位置等于当前选择,我只关闭Navigation Drawer
,如下所示:
String title = null;
invalidateOptionsMenu();
android.support.v4.app.Fragment fragment = null;
if (position == getPrevSelectedItem()) {
// Already selected fragment is being displayed
} else {
switch (position) {
case Numerics.ZERO:
fragment = new DashBoardFragment();
title = fragment.getClass().getSimpleName();
break;
case Numerics.ONE:
break;
case Numerics.TWO:
break;
case Numerics.THREE:
break;
case Numerics.FOUR:
break;
default:
break;
}
if (fragment != null) {
showFragment(fragment, title);
}
setSelectedItem(position);
}
我通过添加到backstack
来添加片段,以便提供对前一个片段的反向导航,如下所示:
if (fragment != null) {
String backStateName = fragment.getClass().getName();
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.dashboard_container, fragment);
mFragmentTransaction.addToBackStack(backStateName);
mFragmentTransaction.commit();
}
问题是:如果我选择项目编号:3,然后选择项目:4,如果我向后导航,上一个选择仍然是4,但我显示的是编号为3的Fragment
。因此,如果我再次从Navigation Drawer
中选择Item no:3,则Fragment
将再次加载。如何解决这个问题??
编辑:
public int getPrevSelectedItem() {
return selectedItem;
}
public void setSelectedItem(int selectedItem) {
this.selectedItem = selectedItem;
}
尝试这个
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.dashboard_container);
if(currentFragment instanceof YouFragmentName)
return
您可以点击菜单查看加载片段的实例
Fragment loadedFragment= getFragmentManager().findFragmentById(R.id.fragmentLoadingSpace);
if( !(loadedFragment instanceof FragmentName1)){
// load fragment
}
我认为不需要else
语句,或者您可以使用else
仅用于关闭drawer
public int prevPosition=-1;
if (getPrevSelectedItem() != prevPosition) {
// Already selected fragment is being displayed
prevPosition =getPrevSelectedItem();
callFragment(position);
}
private void callFragment(int position) {
// TODO Auto-generated method stub
switch (position) {
case Numerics.ZERO:
fragment = new DashBoardFragment();
title = fragment.getClass().getSimpleName();
break;
case Numerics.ONE:
break;
case Numerics.TWO:
break;
case Numerics.THREE:
break;
case Numerics.FOUR:
break;
default:
break;
}
if (fragment != null) {
showFragment(fragment, title);
}
setSelectedItem(position);
}
来自我的评论:
当您按下
back
时,drawer
不会更新,因此您需要在activity
中的onBackPressed()
中添加一些代码,然后根据弹出的BackstackEntry
更新position
。
@Override
public void onBackPressed(){
String backStackEntryName = fragmentManager.getBackStackEntryAt(backCount - 2).getName();
int id = R.id.my_main_frag; //default option
if (MyMainFrag.class.getName().equals(backStackEntryName)){
id = R.id.my_main_frag;
selectedItem = 0;
} else if (MySecondFrag.class.getName().equals(backStackEntryName)){
id = R.id.my_second_frag;
selectedItem = 1;
}
...
navigation.setCheckedItem(id);
super.onBackPressed();
}