当活动由于导航抽屉活动中的方向更改而重新启动时,如何保留相同的片段
问题描述:
我发现许多帖子解释了如何从savedInstanceState
Bundle
中获取Fragment
,但是,由于Activity
可以在4个Fragments
之间交换,我需要一种方法来了解哪个片段还活着,然后在开始改变方向时旋转.
I found many post explaining how get the Fragment
from the savedInstanceState
Bundle
but, because the Activity
can swap between 4 Fragments
, i need a way to know which Fragment was alive before rotate when the orientation started to change.
我有几个片段的原因是因为我使用的是导航抽屉,所以每个菜单项都是一个片段.
The reason i have several Fragments is because i am using Navigation Drawer, so each menu item as a fragment.
答
找到了我自己的答案,那毕竟是一件非常简单的事情.我将解决方案留给了像我这样不熟悉android的人.
Found my own answer and it it was a really simple thing after all. I left the solution here for those who are not familiar to android,like me .
//current fragment
int fragment_id;
//make fragment selection available form the menu resource id
private void setFragment(MenuItem item) {
Fragment fragment = null;
fragment_id = item.getItemId();
switch (fragment_id) {
case R.id.nav_option_1:
fragment = MyFragment1.newInstance(true);
break;
...
//Set fragment
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.content_navigation, fragment);
t.commit();
}
item.setChecked(true);
}
private class DrawerItemClickListener implements NavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
setFragment(item);
return false;
}
}
//save the state
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SAVE_INSTANCE_FRAGMENT_KEY, fragmentid);
}
//restore the saved fragment on create
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
///...
if (savedInstanceState != null) {
int fragment_id = savedInstanceState.getInt(SAVE_INSTANCE_FRAGMENT_KEY);
selectItem(mDrawerList.getMenu().findItem(fragment_id));
} else {
selectItem(mDrawerList.getMenu().findItem(R.id.home_fragment_id));
}
}