从其他活动返回到上一个片段

时间:2016-08-17 08:20:49

标签: android android-fragments android-activity back-stack fragment-backstack

我有一个简单的问题。 我的问题是我有两个活动:

  • 活动A
  • 活动B

活动A 中,我显示4-5个片段。这是主要活动(导航抽屉),所以我在其中显示4-5个片段。

从所有片段重定向到活动B

但是当我从活动B 回来时,我想显示最后打开的片段。

现在它直接打开第一个片段,这是默认的。我想在用户返回第一个活动时打开最后打开的片段。

请帮帮我......

3 个答案:

答案 0 :(得分:0)

如果您的第一个活动随第二个活动而改变,那么前一个活动的片段将因活动生命周期而自行销毁。

您应该使用startActivity打开第一个活动,并将最后一个活动片段存储到字母活动之前。

答案 1 :(得分:0)

调用第二个活动时不使用完成。对于exp:`

Use Host GPU

答案 2 :(得分:0)

您可以使用活动A 中的<div class="parent"> <div class="child"> </div> </div>来保存有关上次打开的片段的信息,并使用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字段。