使用后退按钮切换片段

时间:2013-12-16 00:27:45

标签: android android-fragments

好的,我有一个主要片段的活动,上面有一个菜单。当用户点击菜单项时,另一个片段会动画到屏幕上,并使用以下代码:

FragmentTransaction ft = getFragmentManager().beginTransaction();

ft.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out);
ft.hide(getFragmentManager().findFragmentByTag("menu_fragment"));

Fragment opisFragment = getFragmentManager().findFragmentByTag("opis_fragment");
if (opisFragment == null) {
    opisFragment = new OpisFragment();
    ft.add(R.id.p_container, opisFragment, "opis_fragment");
    ft.commit();
} else {
    ft.show(opisFragment);
}

注意:pr_fragment是当前片段的标签,即具有菜单的片段。

现在,这很好用,但是当我在第二个片段上时,我想添加功能,当用户点击后退按钮时,它将显示第一个片段。使用此代码,当我单击它时,它将退出活动。 谢谢你的帮助!

3 个答案:

答案 0 :(得分:4)

您只需使用FragmentTransaction

addToBackStack(String name)即可
// Showing menu fragment also added in backstack
FragmentTransaction ft = getFragmentManager().beginTransaction();

ft.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out)
  .add(R.id.p_container, menuFragment, "menu_fragment")
  .addToBackStack("menu_fragment")
  .commit();


// Showing opis fragment also added in backstack
FragmentTransaction ft2 = getFragmentManager().beginTransaction();

ft2.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out)
      .add(R.id.p_container, opisFragment, "opis_fragment")
      .addToBackStack("opis_fragment")
      .commit();

假设“opis片段”位于前景,当您按下后退按钮时,“menu_fragment”将显示回前景,再次按下后退按钮将退出活动。

答案 1 :(得分:2)

With this code, when i click back it exits the activity alltogether.

正常,因为您的应用堆栈中只有您的活动。 addToBackStack()方法就是你要找的方法。

if (opisFragment == null) {
    opisFragment = new OpisFragment();
    ft.add(R.id.p_container, opisFragment, "opis_fragment");
    ft.addToBackStack("tag"); // <<< this line
    ft.commit();
}

来自doc

Before you call commit(), however, you might want to call addToBackStack(), in order to add the transaction to a back stack of fragment transactions. This back stack is managed by the activity and allows the user to return to the previous fragment state, by pressing the Back button.

答案 2 :(得分:1)

在mainactivity中,您可以检查片段数,如果片段数超过一个,我们将显示后退按钮

if(getSupportFragmentManager().getBackStackEntryCount() > 0)
            {
               mDrawerToggle.setDrawerIndicatorEnabled(false);
                getSupportActionBar().setDisplayShowHomeEnabled(false);
                getSupportActionBar().setHomeButtonEnabled(true);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }
            else
            {
                mDrawerToggle.setDrawerIndicatorEnabled(true);
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                getSupportActionBar().setHomeButtonEnabled(false);
                getSupportActionBar().setDisplayShowHomeEnabled(true);
            }