Android – ViewPager + PagerAdapter shows blank pages after first two items

androidandroid-viewpager

What's happening: The first two ViewPager pages loaded nicely (ViewPager automatically loads +-1 from current page). When you scroll past these the next pages aren't showing up. GIF demo of the problem below.

Debug info: The pages are being instantiated (see code below) and are successfully added to the ViewPager ArrayList<ItemInfo>mItems (confirmed via Log messages). I recompiled the android.support.v4 library with debug=true set (mmm frameworks/support/v4/ in aosp) and it shows everything working perfectly EXCEPT:

The onLayout and onMeasure methods in ViewPager stop being called after the first two views are loaded. This means the other pages are black because they were never measured&arranged as they should have been. I tried adding different requestLayout() calls at different points to force a layout tree refresh to no avail.

Background: I have a ViewPager instantiated via inflater.inflate and found via view.findViewById(R.layouy.myid). It's directly replacing an old Gallery view, and for testing purposes the PagerAdapter instantiateItem(collection, position) simply does this:

@Override
public Object instantiateItem(View collection, final int position) {
    final TextView tv = new TextView(collection.getContext());
    tv.setText("Looking at page " + position);
    tv.setTextColor(Color.WHITE);
    tv.setBackgroundColor(Color.rgb( (int)(Math.random()*100), (int)(Math.random()*100), (int)(Math.random()*100)));
    tv.setTextSize(22);
    ((ViewPager) collection).addView(tv);
    return tv;
}

Any ideas? It looks to me like some mystery setting in PageView's parents are somehow disabling onLayout PageView

Best Answer

Found my problem. In the parent of the parent of my view someone subclassed LinearLayout and overrode requestLayout() without calling super.requestLayout().

This broke the refreshing of my view hierarchy and prevented onMeasure and onLayout from being called on my ViewPager. Without measuring and laying out the pages they showed up as blank in ViewPager.

Hope this helps someone else out someday. It sure took me forever to figure out.

PRO TIP: android-sdk/tools/hierarchyviewer is incredible. Thank you Android team. Everyone should run it at least once, it can be invaluable in debugging and designing anything UI.

Related Topic