搜尋

首頁  >  問答  >  主體

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

ringa_leeringa_lee2772 天前636

全部回覆(1)我來回復

  • 怪我咯

    怪我咯2017-04-17 11:38:44

    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。

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

    回覆
    0
  • 取消回覆