安卓PagerAdapter中的isViewFromObject()方法有什么用?


public abstract boolean isViewFromObject (View view, Object object)

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.

Parameters
view Page View to check for association with object
object Object to check for association with view
Returns
true if view is associated with the key object object

api这么写,判断view是不是和object相关,还是不大懂要干嘛?

adapter Android pageradapter viewpager

寂靜威尼斯 10 years, 9 months ago

PagerAdapter的一个方法是

public Object instantiateItem (ViewGroup container, int position)

Create the page for the given position. The adapter is responsible for adding the view to the container given here, although it only must ensure this is done by the time it returns from finishUpdate(ViewGroup).

Parameters
container The containing View in which the page will be shown.
position The page position to be instantiated.

Returns
Returns an Object representing the new page. This does not need to be a View, but can be some other container of the page.

该方法声明了返回值不一定是view,可以是任意对象。要知道view的添加是在该方法内部,通过container来添加的,所以这个方法不一定要返回view。

而isViewFromObject方法是用来判断pager的一个view是否和instantiateItem方法返回的object有关联,如果有关联做什么呢?去看代码吧
ViewPager 源码,你去看下addNewItem方法,会找到instantiateItem的使用方法,注意这里的mItems变量。然后你再搜索下isViewFromObject,会发现其被infoForChild方法调用,返回值是ItemInfo。再去看下ItemInfo的结构,其中有一个object对象,该值就是instantiateItem返回的。

也就是说,ViewPager里面用了一个mItems(ArrayList)来存储每个page的信息(ItemInfo),当界面要展示或者发生变化时,需要依据page的当前信息来调整,但此时只能通过view来查找,所以只能遍历mItems通过比较view和object来找到对应的ItemInfo。

说的有些乱,好好看源码就懂了!

nagijng answered 10 years, 9 months ago

Your Answer