安卓:导航抽屉回到第一个碎片

3
我有一个应用程序包含多个导航抽屉中的碎片。
以下是我的代码:
@Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_search).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        fragment = null;

        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new GalleryFragment();
            break;
        case 2:
            fragment = new ContactFragment();
            break;
        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);

    }


    @Override
    public void onBackPressed() {

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .add(R.id.frame_container, fragment).commit();

            int position = 0;
            fragment = new HomeFragment();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        } 



    } 

基本上,它首先进入HomeFragment,当我想要进入其他fragment MediaFragment并决定按下返回按钮回到HomeFragment时,当我再次按下返回按钮关闭应用程序时,它将像Gmail应用程序一样关闭应用程序。我该如何实现这一点?我在我的onBackPressed()中使用的代码出现了问题。每当我进入其他片段时,HomeFragment就会显示出来。有什么建议吗?非常感谢您的帮助。
更新:以前当我在MediaFragment中按下返回按钮时,它会自动关闭应用程序。它不应该是这样的,而应该转到HomeFragment,当它在HomeFragment中并且我点击返回按钮时,它将关闭应用程序。

将该片段添加到后退堆栈并在返回按钮按下时相应地删除它们。 - Raghunandan
@Raghunandan,能给我们一些样例实现吗?谢谢。 - Dunkey
transaction.addToBackStack(null); 而要弹出,请参阅 http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack() - Raghunandan
我尝试使用addToBackStack(null)但它没有达到预期的效果。 - Dunkey
它会正常工作,因为你将其添加到后堆栈并在按下返回键时弹出相同的堆栈。请阅读文档http://developer.android.com/guide/components/fragments.html。 - Raghunandan
2个回答

8

不要在onBackPressed中复制你的代码,为什么不只是跟踪上次选择的位置呢?

int selectedPosition = 0;

private void displayView(int position) {
    ... // All your current code
    selectedPosition = position;
}

@Override
public void onBackPressed() {
    if (selectedPosition != 0) {
        displayView(0);
    } else {
        super.onBackPressed();
}

1

为什么不像@Raghunandan所说的那样,在执行事务时将片段添加到后退栈中。请参见下面的代码:

 if (fragment != null) {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction()
                .replace(R.id.frame_container, fragment).commit(); //Changed from fragmentManager to FragmentTrasaction 

        fragmentTransaction.addToBackStack(null); //this will add the fragment to backstack and hence pressing back will take to previous trasaction

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }

不要添加HomeFragment,否则当您按下返回键时,您将看到一个空白页面(或类似的内容),在退出应用程序之前必须再次按下返回键,因此请避免添加HomeFragment。将除它以外的所有片段添加到后堆栈中,您将能够按照自己的意愿进行操作。此外,当您从片段加载活动时,应用程序会自动在后堆栈中维护它,因此无需担心。
根据您的要求让我知道进展情况。

是的,谢谢。我会尝试这个方法。目前Karakuri提供的解决方案已经解决了我的问题。 - Dunkey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接