Passing data between Fragments in the same Activity

前端 未结 7 1459
清歌不尽
清歌不尽 2021-02-09 12:01

Am working in a project with an Activity that host many fragments. Now I need to share some data (integers, strings, arraylist) between these fragments.

First time i use

7条回答
  •  难免孤独
    2021-02-09 12:24

    You have some options:

    Options 1: If you need to share information between fragments, you can use the SharedPreferences to store the information. This is an example:

    SharedPreferences settings = context.getSharedPreferences("Preferences", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("string1", var);
        editor.putBoolean("bool1", var);
        ...
        editor.commit();
    

    Option 2: If you have instantiated a fragment, you can create a set method to store some kind of information in the fragment. For example, if you want to pass an array of string, you can create an array variable in the fragment (with setter method). Later, when you have instantiated this fragment, you can use the setter method to pass this array to the fragment.

提交回复
热议问题