介紹
作爲一個Android開發者,肯定對RecyclerView並不陌生。它相對ListView來說,有很多的優勢,尤其是在使用方面。
- Adapter
- LayoutManager
- Recycler
- ItemAnimator
- ItemDecoration
Adapter
Adapter實現數據和RecyclerView中的ItemView的關聯工作
LayoutManager
LayoutManager負責在Recyclerview內部測量、定位items,並且決定何時回收用戶不可見View的。通過不同LayoutManager能夠實現不同的滾動效果。
Reycler
Recycler負責管理無用的Item(Scraped和Detached),進行再次複用。Scraped表示依然attach在RecyclerView但是被標記爲removal或者reuse的item。
LayoutManager通常使用Recycler根據給定位置或者ItemId處的數據,來獲取一個ItemView。如果要被複用的Views認爲是dirty,將要求adapter重新進行數據綁定。否則 LLM會迅速完成複用而不需要其他額外工作。沒有調用isLayoutRequested()的clean Item僅僅需要LayoutManager重新定位。
public final class Recycler {
//1,一級緩存
final ArrayList<ViewHolder> mAttachedScrap = new ArrayList<>();
ArrayList<ViewHolder> mChangedScrap = null;
//2. 二級緩存
final ArrayList<ViewHolder> mCachedViews = new ArrayList<ViewHolder>();
//3,三級緩存
private ViewCacheExtension mViewCacheExtension;
//4. 四級緩存
RecycledViewPool mRecyclerPool;
}
ItemAnimator
該類定義了當Adapter中發生變化時,在Items上需要執行的動畫。當自定義動畫時,在實現動畫的方法中,當動畫執行完成一定要調用dispatchAnimationFinished() 通知動畫執行完成。
ItemDecoration
ItemDecoration運行應用程序添加一些額外的繪製和位置偏移,更加Aadapter中的數據集。這對在Item之間添加分割線、高亮、邊界是非常有效的。ItemDecoration的繪製在onDraw在itemViews繪製之前,onDrawOver在最後。
public abstract static class ItemDecoration {
/**
* 該方法在Item繪製之前被調用
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView
*/
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull State state) {
onDraw(c, parent);
}
/**
* 該方法在Item繪製之後被調用
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView.
*/
public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent,
@NonNull State state) {
onDrawOver(c, parent);
}
/**
* item偏移位置信息,如果不想影響item的位置,則設置爲0
*
* @param outRect Rect to receive the output.
* @param view The child view to decorate
* @param parent RecyclerView this ItemDecoration is decorating
* @param state The current state of RecyclerView.
*/
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull State state) {
getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
parent);
}
public void getItemOffsets(@NonNull Rect outRect, int itemPosition,
@NonNull RecyclerView parent) {
outRect.set(0, 0, 0, 0);
}
}
簡單使用
//rcl 是RecyclerView的一個實例
//1. 設置一個動畫(可選項)
rcl.itemAnimator = FlipInLeftYAnimator().apply{
setInterpolator(OvershootInterpolator())
addDuration = 1000
removeDuration = 1000
moveDuration = 1000
changeDuration = 1000
}
//2. 設置layoutManager(必需項)
rcl.layoutManager = LinearLayoutManager(this)
//3. 設置適配(必需項)
rcl.adapter = SimpleAdapter(tmp)
優秀的封裝庫
BRVAH ,本人認爲這是迄今爲止,封裝的最優秀的RecyclerView庫。包括功能如下: