user1590040
user1590040

Reputation: 123

How to know when fragment actually visible in viewpager

I am using 4 fragments inside a ViewPager ,as ViewPager load the previous and next fragment in advance ,and no lifecycle method is called when navigating between fragments. So is there any way to detect when Fragment is actually visible. Thanks in Advance.

Upvotes: 12

Views: 15147

Answers (5)

giorgos.nl
giorgos.nl

Reputation: 2832

Nowadays you can override androidx.fragment.app.onResume and androidx.fragment.app.onPauseto detect if it is visible or not respectively.

Upvotes: 0

Nikunj Paradva
Nikunj Paradva

Reputation: 16077

as per @Matt's answer setUserVisibleHint is deprecated

so here is alternative way for this.

    @Override
    public void setMenuVisibility(boolean isvisible) {
        super.setMenuVisibility(isvisible);
        if (isvisible){
            Log.d("Viewpager", "fragment is visible ");
        }else {
            Log.d("Viewpager", "fragment is not visible ");
        }
    }

Upvotes: 23

Murad Awwad
Murad Awwad

Reputation: 29

Did you try the isVisible method in the fragment?

Upvotes: 2

Mark
Mark

Reputation: 2542

You can use viewPager.getCurrrentItem() to get the currently selected index, and from that you should be able to extrapolate which fragment is shown. However what you probably want is to use addOnPageChangeListener() to add an OnPageChangeListener. This will let you keep track of what page is selected, as it's selected by implementing the onPageSelected(int selected) method.

Upvotes: 2

Matt from vision.app
Matt from vision.app

Reputation: 497

Of course. Assuming that viewPager is your instance of the ViewPager, use: viewPager.getCurrentItem().

Within your Fragment you can check if its instance is visible to the user like so:

@Override
public void setUserVisibleHint(boolean visible) {
    super.setUserVisibleHint(visible);
    if (visible) {
        Log.i("Tag", "Reload fragment");
    }
}

Always make sure that you search for answers throughly before asking your question. For instance, the first place you should check would be: https://developer.android.com/reference/android/support/v4/view/ViewPager.html

Upvotes: 5

Related Questions