29

I am using a FragmentStatePagerAdapter with my View Pager. The Fragment returned is not displayed on the screen if isViewFromObject (View view, Object object) returns false. Why is that?
The developer doc says Determines whether a page View is associated with a specific key object as returned by instantiateItem(ViewGroup, int). This method is required for a PagerAdapter to function properly. But I am not clear with this definition.

Ashwin
  • 12,691
  • 31
  • 118
  • 190

1 Answers1

25

The method instantiateItem(ViewGroup, int) returns Object for a particular view. PagerAdapter implementation is considering this Object as a key value when viewpager changes a page.

So, if we return the view itself from instantiateItem(ViewGroup, int), then our key for that page becomes the view itself. We can check return view == object; from isViewFromObject (View view, Object object) which will always return true and our pages will display :

public boolean isViewFromObject(View view, Object object) {
    return view == object;
}

Some more insights from post https://stackoverflow.com/a/16772250/1994950 :

When you slide, the ViewPager gets view position from an array or instantiates it and compare this view with children of ViewPager with adapters method public boolean isViewFromObject(View view, Object object). The view which equals to object is displayed to the user on ViewPager. If there is no view then the blank screen is displayed.

Here is ViewPager method where the view is compared to object:

ItemInfo infoForChild(View child) {
    for (int i=0; i<mItems.size(); i++) {
        ItemInfo ii = mItems.get(i);
        if (mAdapter.isViewFromObject(child, ii.object)) {
            return ii;
        }
    }
    return null;
}
Daksh Gargas
  • 3,498
  • 2
  • 23
  • 37
Kushal
  • 8,100
  • 9
  • 63
  • 82