交换片段而不是替换?

时间:2018-12-06 14:44:21

标签: android android-fragments

我试图创建类似于WhatsApp,Viber等的底部导航菜单,在这些菜单之间进行切换。我得到了可以正常工作的fragmentManager来替换片段,但是事实证明,当我想返回到我以前访问过的菜单页面之一时,它会重新创建替换的片段。

 @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;

        switch (item.getItemId()) {
            case R.id.navigation_discover:
                fragment = findFragment(RPageFragment.getTAG());
                if(fragment == null){
                    fragment = RPageFragment.newInstance();
                    mFragmentManager.beginTransaction().add(R.id.fragment_container, fragment, fragment.getTag()).commit();
                }
                break;

            case R.id.navigation_booked:

                fragment = findFragment(MapViewFragment.getTAG());
                if(fragment == null){
                    fragment = MapViewFragment.newInstance();
                    mFragmentManager.beginTransaction().add(R.id.fragment_container, fragment, fragment.getTag()).commit();

                }
                break;

            case R.id.navigation_me:
                fragment = findFragment(ProfilePageFragment.getTAG());
                if(fragment == null){
                    fragment = ProfilePageFragment.newInstance();
                    mFragmentManager.beginTransaction().add(R.id.fragment_container, fragment, fragment.getTag()).commit();
                }
                break;
        }
        //Invalid menu option
        if (fragment == null)
            return false;

        mFragmentManager.beginTransaction().replace(R.id.fragment_container,fragment).commit();
        return true;
    }

与Whatsapp的工作方式类似,有什么方法可以在保留片段的视图,状态等的同时交换片段? (例如,我有一个mapView Fragment,当我回到它时,我想展示我离开它的方式,而不是重新创建mapView)

1 个答案:

答案 0 :(得分:0)

您可以使用How to implement a ViewPager with different Fragments / Layouts

您可以简单地检查片段对象null是否像下面的示例所示:

case R.id.navigation_me:
        fragment = findFragment(ProfilePageFragment.getTAG());
        if (fragment == null) {
            mFragmentManager.beginTransaction().show(fragment);
        } else {
            fragment = ProfilePageFragment.newInstance();
            mFragmentManager.beginTransaction().add(R.id.fragment_container, fragment, fragment.getTag()).commit();
        }

        // and you can hide all other fragments here with
        fragmentRPage = findFragment(RPageFragment.getTAG());
        if (fragmentRPage == null) {
            mFragmentManager.beginTransaction().hide(fragmentRPage);
        }
        fragmentMapView = findFragment(MapViewFragment.getTAG());
        if (fragmentMapView == null) {
            mFragmentManager.beginTransaction().hide(fragmentMapView);
        }
        //... and hide other fragments

        break;