0

I have a app with a main activity and fragments. My fragments work but when I switch between them, they refresh and create a new fragment when I switch back. I want the data to save when I switch back and forth, but I can't figure out how to use a bundle to save the values.

This is the code that controls switching between fragments: `private NavigationBarView.OnItemSelectedListener navListener = new BottomNavigationView.OnItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment selectedFragment = null;//used to default to home
                if(item.getItemId() == R.id.nav_home){
                    selectedFragment = new HomeFragment();

                }else if(item.getItemId() == R.id.nav_input){
                    //selectedFragment = new InputFragment();
                    if((InputFragment) getSupportFragmentManager().findFragmentByTag("input_tag") != null){

                        selectedFragment = (InputFragment) getSupportFragmentManager().findFragmentByTag("input_tag");

                    }else{
                        selectedFragment = new InputFragment();
                    }




                }else if(item.getItemId() == R.id.nav_balance){
                    selectedFragment = new BalanceFragment();

                }else if(item.getItemId() == R.id.nav_calendar) {
                    selectedFragment = new CalendarFragment();
                }
                if(selectedFragment == null) selectedFragment = new HomeFragment();
                
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        selectedFragment, "input_tag").commit();

                return true;
            }
        };

}`

I tried reformatting it, and looked through Android Studio forums, but I can't seem to find anything helpful to resolving this problem. I unsuccessfully tried to use tags to save a fragment, but it didn't retain the data. I also tried to use savedInstanceState but it did not work. Any help or directions to start in would be greatly appreciated.

  • You should use hide, show instead of replace or add in transaction. other solution is setOnItemReselectedListener. See this link for more detail [link](https://stackoverflow.com/questions/42362917/fragment-re-created-on-bottom-navigation-view-item-selected) – Anh Luu Mar 30 '22 at 10:19

0 Answers0