Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the role of " isViewFromObject (View view, Object object)" in FragmentStatePagerAdapter?

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.

like image 848
Ashwin Avatar asked Sep 05 '25 04:09

Ashwin


1 Answers

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;
}
like image 150
Kushal Avatar answered Sep 07 '25 19:09

Kushal