Basic communication between two fragments

前端 未结 10 2165
我寻月下人不归
我寻月下人不归 2020-11-22 05:00

I have one activity - MainActivity. Within this activity I have two fragments, both of which I created declaratively within the xml.

I am trying to pas

10条回答
  •  灰色年华
    2020-11-22 05:25

    I give my activity an interface that all the fragments can then use. If you have have many fragments on the same activity, this saves a lot of code re-writing and is a cleaner solution / more modular than making an individual interface for each fragment with similar functions. I also like how it is modular. The downside, is that some fragments will have access to functions they don't need.

        public class MyActivity extends AppCompatActivity
        implements MyActivityInterface {
    
            private List mData; 
    
            @Override
            public List getData(){return mData;}
    
            @Override
            public void setData(List data){mData = data;}
        }
    
    
        public interface MyActivityInterface {
    
            List getData(); 
            void setData(List data);
        }
    
        public class MyFragment extends Fragment {
    
             private MyActivityInterface mActivity; 
             private List activityData; 
    
             public void onButtonPress(){
                  activityData = mActivity.getData()
             }
    
            @Override
            public void onAttach(Context context) {
                super.onAttach(context);
                if (context instanceof MyActivityInterface) {
                    mActivity = (MyActivityInterface) context;
                } else {
                    throw new RuntimeException(context.toString()
                            + " must implement MyActivityInterface");
                }
            }
    
            @Override
            public void onDetach() {
                super.onDetach();
                mActivity = null;
            }
        } 
    

提交回复
热议问题