Matt
Matt

Reputation: 1037

ViewPager - How to know when a cached fragment is displayed

I have a ViewPager using a TabLayout. I am changing pages within a fragment of ViewPager via parentActivity.setCurrentItem() which directs to a sibling Fragment.

Only when I redirect to this fragment from a sibling I would like to display a different view. I am having a issue since the fragment is being cached and OnCreateView is not firing when the fragment is being displayed.

Is there an event that gets fired when a cached fragment is displayed?

Upvotes: 1

Views: 303

Answers (1)

Matt
Matt

Reputation: 1037

Overriding setUserVisible(boolean isVisibleToUser) in the fragment seems to do the trick. This is triggered when the fragment is created and whenever the fragment is displayed.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    ParentActivity parent = (ParentActivity)getActivity();

    if (parent != null){
        String leftMenuToShow = parent.getMenuItemToShowInFragment();
        String elementToShow = parent.getElementToShowInFragment();
    }
}

Upvotes: 1

Related Questions