[Android] Want to save the contents of the view when switching pages with Bottom Navigation
- M.R 
- Aug 20, 2021
- 1 min read
Task
I'm making an app that uses Android's Bottom Navigation. I want to save the data written in TextView etc. when I move the page and come back.
Problem
Normally, if you want to save the contents of the view when you leave Activity or Fragment and come back, save the data in Bundle with onSaveInstanceState () and set the value again with onCreateView () etc. when you come back. However, onSaveInstanceState () is not called when switching pages by BottomNavigation.
Solution
Define a public variable to hold the value in the Activity that implements BottomNavigation (MainActivity this time). In Pause () of each Fragment, put the process to set the value in this public variable, and when it comes back, just take out the value from this public variable.
MainActivity.java
public class MainActivity extends AppCompatActivity {
    public static Bundle args;
    
    public static Bundle get_args(){
        return args;
    }
    
    public static void setArgs(Bundle args_in){
        args=args_in;
    }
}Fragment.java
public void onPause() {
    
    Bundle args;  
    //process to set data to args
    
    MainActivity.setArgs(args);    
    super.onPause();
}
public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    Bundle args=MainActivity.get_args();                         
    //process to set data from args to view
}However, it is not really good to have a value in a public variable that can be accessed from multiple modules like this. It seems that the most essential solution is to customize BottomNavigation, but it seemed to be quite difficult, so I compromised this time.






Comments