显示上一个片段

时间:2012-02-01 18:59:54

标签: android android-fragments back-button

如何删除当前并显示以前的片段?就像我按“后退”按钮

一样

我正在使用这样的结构:

FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.remove(fragment).commit();

但它只删除当前片段,而不显示前一个

3 个答案:

答案 0 :(得分:13)

您必须在FragmentTransaction.addToBackStack(null)处调用添加片段的位置,然后在要删除时调用FragmentManager.popBackStack()

答案 1 :(得分:4)

在您的活动中添加此方法:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if( this.getFragmentManager().getBackStackEntryCount() != 0 ){
                this.getFragmentManager().popBackStack();
                return true;
            }
            // If there are no fragments on stack perform the original back button event
        }

        return super.onKeyDown(keyCode, event);
    }

然后你要改变片段的位置:

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, new YourFragmentName());
transaction.addToBackStack(null); // this is needed for the above code to work
transaction.commit();

答案 2 :(得分:0)

尝试在删除后显示上一个片段:

  FragmentManager fm=getSupportFragmentManager();
  FragmentTransaction ft=fm.beginTransaction();
  ft.remove(fragment).commit();

  previousFragment=(SherlockFragment)getSupportFragmentManager()
    .findFragmentByTag(""+currentTagNum);
    getSupportFragmentManager().beginTransaction()
            .show(mFragment)
            .commit();