[Android] Want to save the contents of the view when switching pages with Bottom Navigation
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.
Recent Posts
See AllIntroduction When I try to upload an app to Google Play Store, the following error occurs Your app is currently targeting API level 31....
Phenomenon When I try to read the data in the database and display it in RecyclerView, nothing is displayed. When I set a breakpoint and...
Phenomenon I want to read data from the database and display it in a list with RecyclerView. There should be more than one registered in...
Comments