Choletski Choletski - 28 days ago 7
Android Question

How to access viewpager's fragment from activity

Suppose such an scenario, we have an activity and 3 fragments, like so:

MyActivity
Frg1
,
Frg2
and
Frg3
.
Frg2
and
Frg3
are embedded into a viewPager. My needs is to trigger
Frg2
from
Frg1
. I made an interface
TriggerActivityFromFrg1
and
MyActivity
implements it, when press button in
Frg1
I call
(getActivity) triggerActivityFromFrg1.trigger()
and method
trigger()
is called in
MyActivity
, the problem is how to trigger
Frg2
from activity?

I'd like to make somehow an interface and between MyActivity and Frg2.

p.s. I don't want to use eventbus.

Answer
  1. Have your Frg2 class also implement the interface:

    public class Frg2 extends Fragment implements TriggerActivityFromFrg1 {
    

    and implement the method

        @Override
        public void trigger() {
            if (getView() != null) {  // see comments below
                // TODO logic here
            }
        }
    
  2. Add a field to your activity to keep track of the target fragment:

        private TriggerActivityFromFrg1 mTarget;
    
  3. Add the register/unregister methods to the activity:

        public synchronized void registerTriggerTarget(TriggerActivityFromFrg1 listener) {
            mTarget = listener;
        }
    
        public synchronized void unregisterTriggerTarget(TriggerActivityFromFrg1 listener) {
            if (mTarget == listener) {
                mTarget = null;
            }
        }
    
  4. Make the trigger method in your activity like this:

        public void trigger() {
            if (mTarget != null) {
                mTarget.trigger();
            }
        }
    
  5. Override onAttach() and onDetach() in Frg2 to register/unregister:

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MyActivity) activity).registerTriggerTarget(this);
        }
    
        @Override
        public void onDetach() {
            ((MyActivity) getActivity()).unregisterTriggerTarget(this);
            super.onDetach();
        }
    

Congratulations, you just built your own mini event bus.

There's a reason you have to add all this code, and that's because ViewPager won't create fragments until it needs them. Also it decouples MyActivity from Frg2.

Another thing to keep in mind if extending FragmentPagerAdapter is that the fragment will stay in memory even if the view is destroyed, so make sure you check that the fragment has a valid view, i.e. if (getView() != null)

Comments