0

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.

user3089214
  • 267
  • 3
  • 14
  • Since you are loading the fragment inside the main activity, the items in the fragment should be accessible from the main activity if you use `findviewbyid` to fetch the items in the fragment on to the main activity. – jgm Jun 12 '16 at 01:41
  • Best way to do it looks like:http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/ – user3089214 Jun 12 '16 at 01:44
  • try this.. video on youtube.... https://www.youtube.com/watch?v=WssDyQ2m4rY – Muhammad Waleed Jun 12 '16 at 05:46

3 Answers3

2

You need to put OnFragmentInteractionListener interface in your fragments:

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

and implement it in your activity by "implements .OnFragmentInteractionListener" and including the following method in your activity

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

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

Vadik Sirekanyan
  • 3,332
  • 1
  • 22
  • 29
usajnf
  • 522
  • 3
  • 11
0

The best way is using some kind of observer pattern where activity can register to fragment on attach and implement interface which will be called by fragment everytime things changes inside.

For more detailed answer:

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

user3089214
  • 267
  • 3
  • 14
0

You need to use this library and you can communicate with anywhere in your app:

https://github.com/greenrobot/EventBus

xblack
  • 581
  • 2
  • 8