How to save state of fragment in navigation drawer

房东的猫 提交于 2020-01-07 05:25:10

问题


I'm using google navigation drawer library from the following link... https://github.com/Arasthel/GoogleNavigationDrawerMenu

See code below:

    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");
            }
        }
    });

My fragments are using async task and whenever I switch between these fragments the async task is loading again.

So How can I save the state of the fragment?


回答1:


Instead of creating new fragment every time you can keep an array of fragments and just return the same object:

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");
        }
    }
});


来源:https://stackoverflow.com/questions/24882470/how-to-save-state-of-fragment-in-navigation-drawer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!