Communicating between a fragment and an activity - best practices

后端 未结 9 1325
予麋鹿
予麋鹿 2020-11-22 02:45

This question is mostly to solicit opinions on the best way to handle my app. I have three fragments being handled by one activity. Fragment A has one clickable element th

9条回答
  •  别那么骄傲
    2020-11-22 03:35

    It is implemented by a Callback interface:

    First of all, we have to make an interface:

    public interface UpdateFrag {
         void updatefrag();
    }
    

    In the Activity do the following code:

    UpdateFrag updatfrag ;
    
    public void updateApi(UpdateFrag listener) {
            updatfrag = listener;
    }
    

    from the event from where the callback has to fire in the Activity:

    updatfrag.updatefrag();
    

    In the Fragment implement the interface in CreateView do the following code:

     ((Home)getActivity()).updateApi(new UpdateFrag() {
            @Override
            public void updatefrag() {
                  .....your stuff......
            }
     });
    

提交回复
热议问题