Create
interface
public interface ListenFromActivity { void doSomethingInFragment();}
In Activity class keep refrence of ListenFromActivity interface
public ListenFromActivity activityListener;
Make
public method to set listener
public void setActivityListener(ListenFromActivity activityListener) { this.activityListener = activityListener; }
Add some
trigger point in activity class, here I have used user interaction
@Override public void onUserInteraction() { super.onUserInteraction();
if (null != activityListener) { activityListener.doSomethingInFragment(); } }
Now in Fragment class
make
your fragment implement interface class
public class SomeFragment extends Fragment implements ListenFromActivity
Android
studio will prompt you to implement method of interface in fragment
void doSomethingInFragment(){//Add
your code here }
Final
part part listener instance to activity like this in fragment onCreate method
((ListnerActivity) getActivity()).setActivityListener(SomeFragment.this);
DONE!!.
now you can call fragment method from activity.