碰到這樣一個需求,有一個關(guān)注列表,點(diǎn)擊列表上的關(guān)注按鈕可以取消關(guān)注傻唾。
首先列表這里選擇的是RecyclerView未荒,實(shí)現(xiàn)起來也較為簡單,實(shí)現(xiàn)Adapter綁定數(shù)據(jù)就可以了
但是取消關(guān)注后需要將該用戶從列表里移除接箫,為了不整體刷新攒读,所以選擇使用notifyItemRemoved而不是notifyDataSetChanged方法,因?yàn)閚otifyItemRemoved不會刪除adapter中數(shù)據(jù)集中真實(shí)的元素辛友,因此還需要調(diào)用dataList.remove(i)
但是測試的時候發(fā)現(xiàn)了一個問題:
點(diǎn)擊第一個用戶薄扁,成功刪除,nice.
這時候原來的第二個用戶成了第一個用戶废累,按照之前的邏輯邓梅,這個地方的position應(yīng)該是0。但是邑滨,點(diǎn)擊之后刪除的是現(xiàn)在的第二個用戶日缨,也就是說position是1。
網(wǎng)上搜索后發(fā)現(xiàn)驼修,在notifyItemRemoved雖然移除了視圖殿遂,但是沒有進(jìn)行重新bind的過程,因此position還是之前的position,因此需要調(diào)用notifyItemRangeChanged方法來告訴應(yīng)用position位置需要重新計算
* Notify any registered observers that the <code>itemCount</code> items starting at
* position <code>positionStart</code> have changed.
* Equivalent to calling <code>notifyItemRangeChanged(position, itemCount, null);</code>.
*
* <p>This is an item change event, not a structural change event. It indicates that
* any reflection of the data in the given position range is out of date and should
* be updated. The items in the given range retain the same identity.</p>
*
* @param positionStart Position of the first item that has changed
* @param itemCount Number of items that have changed
*
* @see #notifyItemChanged(int)
*/
上面一段來自RecyclerView源碼中的注釋乙各,notifyItemRangeChanged方法需要兩個參數(shù)墨礁,第一個來指定從哪里開始數(shù)據(jù)進(jìn)行了變化,第二個參數(shù)需要指定總共變化了多少個數(shù)據(jù)耳峦。
在最開始提到的需求下恩静,positionStart應(yīng)該等于要刪除的那個數(shù)據(jù)的坐標(biāo),itemCount應(yīng)該為從positionStart開始到數(shù)據(jù)列表最后蹲坷,但是為了方便就直接填getItemCount()更新所有數(shù)據(jù)了