Passing data between Fragments in the same Activity

前端 未结 7 1442
清歌不尽
清歌不尽 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:28

    The easiest way to do this is to use Bundle. You do something like this:

    Fragment A:

    Bundle b = new Bundle();
    b.putString("Key", "YourValue");
    b.putInt("YourKey", 1);
    
    FragmentB fragB = new FragmentB();
    fragB.setArguments(b); 
    getFragmentManager().beginTransaction().replace(R.id.your_container, fragB);
    

    Fragment B:

    Bundle b = this.getArguments();
    if(b != null){
       int i = b.getInt("YourKey");
       String s =b.getString("Key");
    }
    

    This is the easiest way that I have found to send data from one fragment to another. Hope it helps someone.

提交回复
热议问题