1. 程式人生 > >adapter 中使用 getItemViewType 遇到的問題

adapter 中使用 getItemViewType 遇到的問題

工作中遇到在adapter  中顯示2種類型的樣式,需要在adapter 種重寫 getItemViewType,和  getViewTypeCount 這兩個方法,之前在用的時候沒有太注意,在重寫getItemViewType 的時候對於不同的ViewType 返回 1和2 ,後來老是奔潰,進去看原始碼,原始碼對這個方法的註釋為:

/**
 * Get the type of View that will be created by {@link #getView} for the specified item.
 * 
 * @param position The position of the item within the adapter's data set whose view type we
* want. * @return An integer representing the type of View. Two views should share the same type if one * can be converted to the other in {@link #getView}. Note: Integers must be in the * range 0 to {@link #getViewTypeCount} - 1. {@link #IGNORE_ITEM_VIEW_TYPE} can * also be returned.
* @see #IGNORE_ITEM_VIEW_TYPE */

這裡明確指出 返回的值一定要從0 到 getViewTypeCount -1,可以看出,這個地方gitItemViewType 返回的值不是隨便亂設定的。android 原始碼是這麼用,

/**
 * @return A view from the ScrapViews collection. These are unordered.
 */
View getScrapView(int position) {
    final int whichScrap = mAdapter.getItemViewType(position);
if (whichScrap < 0) { return null; } if (mViewTypeCount == 1) { return retrieveFromScrap(mCurrentScrap, position); } else if (whichScrap < mScrapViews.length) { return retrieveFromScrap(mScrapViews[whichScrap], position); } return null; }

這裡是itemViewType() 是mScrapViews 中的index, 難怪當我們把  getItemViewType 設定成1,2 的時候,會出現indexOutIndexException 這個錯誤,對於mScrapViews  

從scrapView中獲取相應型別的view,這個陣列是在RecycleBin中,這個RecycleBin 的主要功能是為了更方便的複用view,他有兩個層級,分別是ActiveViews和ScrapViews。ActiveViews是當前展示在螢幕上的 layout,但是最終所有的views 都將降級為ScrapViews。 ScrapViews  是被回收掉的不在螢幕展示的view, 他為了避免adapter 重新建立view。