Passing data between Fragments in the same Activity

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

    I think the best solution for you is to have the variables inside the main activity and access them from fragments. I mean, if you have to do THE SAME in all fragments, you can write the code inside the activity and just call the method you need.

    You need to use an interface for this purpose

    public interface DataCommunication {
        public String getMyVariableX();
        public void setMyVariableX(String x);
        public int getMyVariableY();
        public void setMyVariableY(int y);
    }
    

    Then, implement it inside your activity

    public class MainActivity extends Activity implements DataCommunication {
    
        private String x;
        private int y;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            ...   
        }
    
        ...
    
        @Override
        public String getMyVariableX(){
            return x;
        }
    
        @Override
        public void setMyVariableX(String x){
            //do whatever or just set
            this.x = x;
        }
    
        @Override
        public int getMyVariableY(){
            return y;
        }
    
        @Override
        public void setMyVariableY(int y){
            //do whatever or just set
            this.y = y;
        }
    
        ...
    

    Then, attach the activity in ALL your fragments:

    public class Fragment_1 extends Fragment{
    
        DataCommunication mCallback;
    
     @Override
        public void onAttach(Context context) {
            super.onAttach(context);
    
            // This makes sure that the container activity has implemented
            // the callback interface. If not, it throws an exception
            try {
                mCallback = (DataCommunication) context;
            } catch (ClassCastException e) {
                throw new ClassCastException(context.toString()
                        + " must implement DataCommunication");
            }
        }
    
        ...
    

    And finally, when you need to use a variable inside a fragment, just use get and se methods you've created

    https://developer.android.com/training/basics/fragments/communicating.html

提交回复
热议问题