【问题标题】:Return to previous fragment from other activity从其他活动返回到上一个片段
【发布时间】:2016-08-17 08:20:48
【问题描述】:

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

  • 活动 A
  • 活动 B

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

它从所有片段重定向到Activity B

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

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

请帮帮我...

【问题讨论】:

  • 您能否提供您的第一个活动初始化并打开默认片段的部分代码(我假设它是您在活动 A 中的 onCreate 方法)?谢谢。
  • mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); if (navigationView != null) { Home homeFragment = new Home(); homeFragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, homeFragment, "HOME").commit(); setupDrawerContent(navigationView); }
  • 这就是我在 oncreate 中初始化默认片段的方式
  • 能否将其粘贴在您的问题中以提高可读性?

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


【解决方案1】:

您可以在Activity A中使用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);
    }
}

别忘了更新onNavigationItemSelected回调中的currentOpenedFragment字段。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

       Intent i = new Intent(getApplicationContext(), ActivityB.class);
       startActivity(i);
       //finish(); `
      

      【讨论】:

      • 我没用过finish();
      • 错误答案。您必须考虑活动生命周期
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多