追溯源碼解決android疑難問題1--Viewpager之notifyDataSetChanged無重新整理

來源:互聯網
上載者:User

最近項目結束,搞了一次代碼分享。其中一位同學分享了一下自己在解決問題過程中的一些心得體會,感覺受益匪淺。整理出來,分享給大家。
建議使用自己編譯的android os和虛擬機器,這樣就可以調試android系統中的任何組件。簡單說來,深入android源碼,去尋找解決問題的答案。這事兒說起來簡單,實際做起來還是有些難度的。我也曾經嘗試著去看過,沒看一會兒就暈了。

所以還是有針對性的去看源碼,效率會高一些。

廢話不多說,先看第一個樣本。

Viewpager在調用notifyDataSetChanged()時,介面無重新整理。
相信很多做過Viewpager的同學肯定遇到過這個問題,這個是bug還是android就是如此設計的,我們不做討論。總之,它確實影響我們功能的實現了。

可能不少同學選擇為Viewpager重新設定一遍適配器adapter,達到重新整理的目的。但是這種方法在大多數情況下,是有問題的。

追蹤原始碼:
為什麼調用資料更新的方法,Viewpager卻沒有更新呢,我們跟進該方法的原始碼看一下。

首先查看適配器調用的super.notifyDataSetChanged(),該方法調到抽象基類PagerAdapter.notifyDataSetChanged()中:

    /**     * This method should be called by the application if the data backing this adapter has changed     * and associated views should update.     */    public void notifyDataSetChanged() {        mObservable.notifyChanged();    }  
  注釋裡說到,當附加在適配器上的資料發生變化時,應該調用該方法重新整理資料。該方法調用了一個mObservable .notifyChanged();

我們繼續跟進這個方法,進入DataSetObservable類中,發現這樣一段代碼:

   /**     * Invokes {@link DataSetObserver#onChanged} on each observer.     * Called when the contents of the data set have changed.  The recipient     * will obtain the new contents the next time it queries the data set.     */    public void notifyChanged() {        synchronized(mObservers ) {            // since onChanged() is implemented by the app, it could do anything, including            // removing itself from {@link mObservers} - and that could cause problems if            // an iterator is used on the ArrayList {@link mObservers}.            // to avoid such problems, just march thru the list in the reverse order.            for (int i = mObservers .size() - 1; i >= 0; i--) {                mObservers.get(i).onChanged();            }        }    }

, 我們來看一下都有誰使用了這個抽象類別呢,快速鍵 ctrl + alt + H ,在眾多的調用者當中,我們發現了Viewpager的身影:

      void dataSetChanged () {        // This method only gets called if our observer is attached, so mAdapter is non-null.        boolean needPopulate = mItems .size() < mOffscreenPageLimit * 2 + 1 &&                mItems.size() < mAdapter.getCount();        int newCurrItem = mCurItem ;        boolean isUpdating = false;        for (int i = 0; i < mItems.size(); i++) {            final ItemInfo ii = mItems .get(i);            final int newPos = mAdapter.getItemPosition(ii.object );            if (newPos == PagerAdapter.POSITION_UNCHANGED ) {                continue;            }            if (newPos == PagerAdapter.POSITION_NONE) {                mItems.remove(i);                i--;                if (!isUpdating) {                    mAdapter.startUpdate( this);                    isUpdating = true;                }                mAdapter.destroyItem( this, ii.position , ii.object);                needPopulate = true;                if (mCurItem == ii.position ) {                    // Keep the current item in the valid range                    newCurrItem = Math. max(0, Math.min(mCurItem, mAdapter.getCount() - 1));                    needPopulate = true;                }                continue;            }            if (ii.position != newPos) {                if (ii.position == mCurItem ) {                    // Our current item changed position. Follow it.                    newCurrItem = newPos;                }                ii. position = newPos;                needPopulate = true;            }        }        if (isUpdating) {            mAdapter.finishUpdate( this);        }        Collections. sort(mItems, COMPARATOR);        if (needPopulate) {            // Reset our known page widths; populate will recompute them.            final int childCount = getChildCount();            for (int i = 0; i < childCount; i++) {                final View child = getChildAt(i);                final LayoutParams lp = (LayoutParams) child.getLayoutParams();                if (!lp.isDecor ) {                    lp. widthFactor = 0.f;                }            }            setCurrentItemInternal(newCurrItem, false, true);            requestLayout();        }    }
重點看這樣一行代碼:

   final int newPos = mAdapter.getItemPosition(ii.object );   if (newPos == PagerAdapter.POSITION_UNCHANGED ) {         continue ;   }
仔細看了一下這段代碼的大意,官方的解釋是:

Called when the host view is attempting to determine if an item's position has changed. Returns POSITION_UNCHANGED if the position of the given item has not changed or POSITION_NONE if the item is no longer present in the adapter.
The default implementation assumes that items will never change position and always returns POSITION_UNCHANGED.

解決方案:所以我們可以嘗試著修改適配器的寫法,覆蓋getItemPosition()方法,當調用notifyDataSetChanged時,讓getItemPosition方法人為的返回POSITION_NONE,從而達到強迫viewpager重繪所有item的目的。

具體代碼如下:
class SearchAdapter extends PagerAdapter {         private int mChildCount = 0;     @Override     public void notifyDataSetChanged() {                    mChildCount = getCount();           super.notifyDataSetChanged();     }     @Override     public int getItemPosition(Object object)   {                     if ( mChildCount > 0) {           mChildCount --;           return POSITION_NONE;           }           return super.getItemPosition(object);     } }

大家可以嘗試一下,歡迎拍磚。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.