简体   繁体   中英

How to save state of fragment with BottomNavigationBar?

I have BottomNavigationBar with five tabs. In that fragment, I'm loading data from the server. My issue is that Fragment each time loads data on changing tab. I don't want to load data every time.

I know it can be possible using onSaveInstanceState() , but it is useful to save a small amount of data.

And one thing, There is all fragments in-app, so can't get any solution for my problem. Any help would be appreciated

MainActivity:

 private boolean loadFragment(Fragment fragment) {
    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentContainer, fragment)
                .commit();
        return true;
    }
    return false;
}

Do You write Your application in MVVM architectural pattern? If so I think You can use Shared ViewModel .
Android docs. Share data between fragments
Stack Overflow: Sharing data between fragments using new architecture component ViewModel
I think this might help You. If You load data in ViewModel class You can use it in all fragments even when Your app stoped You don't have to load it again.

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