Best way to communicate between activity and fragment

时间:2016-06-12 01:33:03

标签: android android-fragments android-activity

I'm creating an activity which have viewpager to show multiple fragments and also an button 'Continue'. Button is used to move to next fragment, mimicing swipe nature of viewpager.

I have kept my fragments very independent from activity and want to communicate the results to parent activity whenever something happens like edit text value changed inside fragment.

What should be best way to inform activity about happening changes inside fragment? Fragment shouldn't know who is parent activity.

Thanks in advance.

3 个答案:

答案 0 :(得分:2)

您需要在片段中放置OnFragmentInteractionListener接口:

public interface OnFragmentInteractionListener {
    public void onFragmentInteraction(String id);
}

并在您的活动中实施 “implements .OnFragmentInteractionListener” 并在您的活动中包含以下方法

@Override
public void onFragmentInteraction(String id) {
    // Do something here
}

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

答案 1 :(得分:0)

最好的方法是使用某种观察者模式,其中活动可以在附加和实现接口上注册片段,每当内部发生变化时,片段都会调用它。

更详细的答案:

http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/

答案 2 :(得分:0)

您需要使用此库,并且可以与应用中的任何位置进行通信:

https://github.com/greenrobot/EventBus