Hiren Hiren - 1 year ago 80
Android Question

How to make sure current Fragment is visible in ViewPager

I have 3

Fragments
inside a
ViewPager
. I want to execute network calls only when the
Fragment
is visible to the user. Currently I am using the following method:

@Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
isVisible = true;

} else {
isVisible = false;

}

}


But the problem with the above method is giving me
getActivity()
null in the 1st
Fragment
. This method works fine in 2nd and 3rd
Fragment
.
I tried using
setUserVisibleHint()
but that is returning true every time.
What can be the bullet-proof solution for the above problem? I want a method that can tell me if the
Fragment
is visible or not to the user along with
getActivity()!=null
.

Thanks in advance.

Answer Source

While trying setUserVisibleHint(), When you are using the same Class for all 3 Fragment, You will get called 3 times or 2 times based on the position it will get call setUserVisibleHint(), but in that one time it will be true and remaining times will be false, because currently, one Fragment will be visible.

In that case Instead of checking only true or false, just check with true with some Id(make sure its null-pointer check, Example if you moving from 2nd position to 3rd, then 1st position arguments which we send through setArguments will be null).

Example: I have one Fragment class using for 3 Fragment in my ViewPager, I want to animate some View when user come focus to the Fragment.

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

    if (isVisibleToUser) {
        startAnimation(); // If I comment this line my View will be hidden always because I am hiding the View when it's not focused on the user
    } else {
        checkAndHide();
    }
}

public void startAnimation() {
    // View might not created, when calling this, because setUserVisibleHint get call before onCreateView()
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mView != null) {

            }
        }
    }, 500);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download