简体   繁体   中英

Android navigation component how save BottomNavigationBar fragments state

I'm used the NavigationExtensions.kt class from the NavigationAdvancedSample to implement the BottomNavigationBar navigation. as the following:

 bottomNavigationView = findViewById(R.id.bottom_nav)
        val navGraphIds = listOf(R.navigation.home, R.navigation.category, R.navigation.cart, R.navigation.account, R.navigation.jak)
        // Setup the bottom navigation view with a list of navigation graphs
        val controller = bottomNavigationView?.setupWithNavController(
                navGraphIds = navGraphIds,
                fragmentManager = supportFragmentManager,
                containerId = R.id.nav_host_container,
                intent = intent
        )

        // Whenever the selected controller changes, setup the action bar.
        controller?.observe(this, Observer { navController ->
            setupActionBarWithNavController(navController)
        })
        currentNavController = controlle

I'm trying to save the fragment states for every tap, but I don't know how to do it. All classes and fragments are written in java, only the main activity and NavigationExtensions in Kotlin. Navigation implementations:

implementation "androidx.navigation:navigation-fragment:2.2.0-alpha03"
implementation "androidx.navigation:navigation-ui:2.2.0-alpha03"
implementation "androidx.navigation:navigation-fragment-ktx:2.2.0-alpha03"
implementation "androidx.navigation:navigation-ui-ktx:2.2.0-alpha03"

and this is one of my Fragment onCreateView method:

@Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mViewModel = ViewModelProviders.of(this).get(HomePageViewModel.class);
        binding = DataBindingUtil.inflate(inflater, R.layout.home_page_fragment, container, false);
        binding.setLifecycleOwner(this);
        mViewModel.init();
        binding.setViewModel(mViewModel);
        setHasOptionsMenu(true);
        ((MainActivity) getActivity()).homeToolbarWithImage();
        ShowMainList();
        binding.swiperefresh.setOnRefreshListener(this);
        return binding.getRoot();
    }

Can anyone help me to slove the problem?

You can use "FragmentPagerAdapter" for saving the state of diff fragments. Add your fragments using the "FragmentPagerAdapter". Also don't worry, if you are unable to understand the java classes. You can still you these directly within your kotlin classes. Kotline provides interoperability because of which you can use java and kotiln classes together in same project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM