我有个简单的问题。我的问题是我有两个活动:
在活动中,I显示4-5个片段.这是主要的活动(导航抽屉),所以我在其中显示4-5个片段。
从所有片段重定向到活动B。
但是,当我从Activity 回来时,我想显示最后一个打开的片段。
现在它直接打开第一个片段,这是默认的。当用户返回到第一个活动时,我想打开最后一个打开的片段。
请帮帮我..。
发布于 2016-08-17 08:32:21
调用第二次活动时不使用finish。代表exp:`
Intent i = new Intent(getApplicationContext(), ActivityB.class);
startActivity(i);
//finish(); `发布于 2016-08-17 10:07:23
您可以在onSaveInstanceState活动中使用保存有关上次打开的片段的信息,并使用onRestoreInstanceState/onCreate恢复该信息。例如:
private static final String LAST_OPENED_FRAGMENT_REF = "LAST_OPENED_FRAGMENT_REF";
private static final int HOME_FRAGMENT = 0;
private static final int OTHER_FRAGMENT = 1;
private int currentOpenedFragment = HOME_FRAGMENT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (savedInstanceState != null) {
currentOpenedFragment = savedInstanceState.getInt(LAST_OPENED_FRAGMENT_REF);
}
if (navigationView != null) {
Fragment fragment = initFragmentByType(currentOpenedFragment);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
setupDrawerContent(navigationView);
}
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(LAST_OPENED_FRAGMENT_REF, currentOpenedFragment);
}
private Fragment initFragmentByType(int type) {
switch(type) {
case HOME_FRAGMENT: return new Home();
case OTHER_FRAGMENT: return new Other();
default: throw new IllegalArgumentException("There is no type: " + type);
}
}不要忘记在currentOpenedFragment回调中更新onNavigationItemSelected字段。
https://stackoverflow.com/questions/38991506
复制相似问题