隨著listview的代碼因?yàn)樘砑觙eature而變得不可維護(hù)出吹,google開始創(chuàng)建RecyclerView
ListView的缺點(diǎn):
- 重復(fù)的功能
- 動(dòng)畫不方便實(shí)現(xiàn)
RecyclerView 基于幾大組件實(shí)現(xiàn)珍德,代碼組織更加合理髓需。
LayoutManager
- 排布item在屏幕上的位置
- handle the scroll
- Focus Traversal
- Accessibility
Adapter
- create view and view holder
- bind an item to a viewholder
- notify recyclerView about changes
- item interaction handling (click etc)
- multiple view type
- Recycler recovery(onFailedToRecycleView)
- Granular data change events
ViewHolder
- viewHolder 的創(chuàng)建流程:
- bind viewholder
- view 的展示
- view 的回收
注意:回收的時(shí)候先將viewholder放入cache中,這樣下次如果再展示這個(gè)position的view虎忌,可以直接從cache中取共螺,不用再跟adapter打交道。cache中evict的老的數(shù)據(jù)再放入recycle pool中
如果view從屏幕上去除時(shí)葛假,需要做刪除動(dòng)畫障陶,則會(huì)被RecycleView臨時(shí)加入到viewGroup中,LayoutManager并不知道聊训。然后由ItemAnimator進(jìn)行動(dòng)畫操作抱究,動(dòng)畫完成后,才對view進(jìn)行回收
如果在回收時(shí)带斑,發(fā)現(xiàn)view正處于transient state(正在動(dòng)畫鼓寺,或者edit text中的內(nèi)容被選中),會(huì)導(dǎo)致recycle pool無法回收遏暴,這時(shí)會(huì)調(diào)用adapter的onFailedToRecycle
侄刽,給adapter最后一次機(jī)會(huì)去清除transient state,以使view可以被回收朋凉,adpater可以清除動(dòng)畫州丹,并返回true,也可以返回false杂彭,這樣viewholder會(huì)被銷毀
還有一種情況會(huì)導(dǎo)致viewholder銷毀墓毒,recycle pool對于每種type的view,只能回收一定的數(shù)量亲怠,一旦超過這個(gè)數(shù)量所计,多余的就會(huì)被銷毀。
ChildHelper
因?yàn)閘ayoutManager可能會(huì)和ItemAnimator對一個(gè)view產(chǎn)生沖突的操作(remove view vs animation)团秽,引入childHelper為layoutmaanger提供一個(gè)虛擬的視圖主胧,等itemAnimator的動(dòng)畫完成后才進(jìn)行真正view的操作
Adapter Helper
Adapter Helper記錄adapter上的notify操作,并對notify操作進(jìn)行reorder
ItemDecoration
- 對每個(gè)子view添加decoration
- add offset to view bound
RecycledViewPool
ItemTouchHelper
方便的實(shí)現(xiàn)drag&drop习勤, swipe
Extra:
- 如果數(shù)據(jù)沒有更新踪栋,則不會(huì)重新bindViewHolder
- onBindViewHolder中傳入position不一定是最終在adapter中的位置,因?yàn)閍dapter中數(shù)據(jù)改變了图毕,不一定馬上反映到view的位置上
- change with payload
當(dāng)notifyItemChange時(shí)傳入了payload夷都,當(dāng)前position會(huì)使用同一viewholder,只用部分綁定就可以了予颤,如果沒有payload則
不要在create里面返回同一個(gè)view
adapter position 有可能與layout position不一致until next layout