如何在导航抽屉中保存片段的状态

时间:2014-07-22 08:31:49

标签: android android-fragments navigation-drawer

我正在使用以下链接中的Google导航抽屉库... https://github.com/Arasthel/GoogleNavigationDrawerMenu

见下面的代码:

    mDrawer.setOnNavigationSectionSelected(new GoogleNavigationDrawer.OnNavigationSectionSelected() {
        @Override
        public void onSectionSelected(View v, int i, long l) {
            Fragment fragment = null;
            switch (i) {
            case 0:
                // fragment = new HomeFragment();
                break;
            case 1:
                fragment = new NewsFragment();

                break;
            case 2:
                fragment = new TransferFragment();
                break;
            case 3:
                fragment = new BlogsFragment();
                break;
            case 4:
                fragment = new FixturesFragment();
                break;
            case 5:
                fragment = new BestXIFragment();
                break;
            case 6:
                fragment = new FeedFragment();

                break;

            default:
                break;
            }
            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.main, fragment).commit();

            } else {
                // error in creating fragment
                Log.e("MainActivity", "Error in creating fragment");
            }
        }
    });

我的片段正在使用异步任务,每当我在这些片段之间切换时,异步任务就会再次加载。

那么如何保存片段的状态呢?

1 个答案:

答案 0 :(得分:0)

每次都可以保留一个片段数组并返回相同的对象,而不是创建新的片段:

mDrawer.setOnNavigationSectionSelected(new GoogleNavigationDrawer.OnNavigationSectionSelected() {

Fragment[] fragments ={new HomeFragment(),new NewsFragment(),  new TransferFragment(), new BlogsFragment(),new FixturesFragment() , new BestXIFragment(),new FeedFragment()};
 @Override

    public void onSectionSelected(View v, int i, long l) {

        if (fragment[i] != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.main, fragments[i]).commit();

        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }
});