android - 安卓PagerAdapter中的isViewFromObject()方法有什么用?
ringa_lee
ringa_lee 2017-04-17 11:36:44
0
1
638

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相关,还是不大懂要干嘛?

ringa_lee
ringa_lee

ringa_lee

全部回覆(1)
刘奇

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(Iroup).

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。

說的有些亂,好好看源碼就懂了!

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板