top of page

[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 All

Comments


category

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page