Android best practices for Fragment to Activity communications

后端 未结 5 1773
误落风尘
误落风尘 2021-01-18 10:42

I am new to Android Fragment and trying to learn Fragment to Activity communications. What is the better approach(best practice) in Android for Fragment to Activity communic

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-18 11:06

    First pattern is best when your fragment is used only by one activity. Second approach is needed if you want your fragment to communicate with some other objects not the activity that hosts fragment. If you always want to communicate with hosting activity callback is not needed. Just create an interface and implement it on as many activities as needed. Then in your fragment cast activity returned by getActivity().

    MyInterface myInteface = (MyInterface) getActivity();
    myinterface.somemethod();
    

    You can even check if activity implements needed interface(s) etc.

提交回复
热议问题