Question

I'm using a ViewPager to display 2 Fragments as tabs. Once the according activity is loaded, both fragments are loaded immediatly, while only the first one is visible to the user.

Therefore view.isShown() is not sufficent for testing, as this method returns true for the second fragment which is not visible to the user.

ViewAsserts.assertOnScreen(decorView, view) seems to behave the same way and is therefore useless for solving this problem.

I'm aware that some similar questions have been asked, but none of their answers is satisfying my needs. So how to test this behavior (using Robotium)?

Solution:

I solved it according to Leon's suggestion by using a flag within the fragment like this:

private static boolean isVisibleToUser = false;

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

    MyFragment.isVisibleToUser = isVisibleToUser;
}

public static boolean isVisibleToUser() {
    return isVisibleToUser;
}

implementing it as a static method I can use it in my test this way:

assertTrue(MyFragment.isVisibleToUser());

the only drawback to this solution is that I have to implement these 2 methods in every single Fragment I want to test this way... any improvements?

Was it helpful?

Solution

You could override setUserVisibleHint inside your fragment like this:

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

    if (isVisibleToUser) { 
         //Fragment is selected in ViewPager
         //Put your "on appear" validation/loading here
    }
}

This method will fire every time you show or hide the fragment in the ViewPager.

As opposed to view.isShown() this method does take a "loaded but not visible" state into account.

OTHER TIPS

use OnPageChangedListener to detect changes and maintain a reference to the currently visible fragment/page.

http://developer.android.com/reference/android/support/v4/view/ViewPager.OnPageChangeListener.html

Alternatively GetCurrentItem() may work for you as detailed here: How do you get the current page number of a ViewPager for Android?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top