要通過ItemDecoration改變列表項的顯示效果,可以創(chuàng)建一個自定義的ItemDecoration類,并重寫其onDraw()和onDrawOver()方法來實現(xiàn)想要的效果。例如,可以在onDraw()方法中繪制分隔線或背景色,或者在onDrawOver()方法中繪制懸浮的標(biāo)簽等。然后將該ItemDecoration類應(yīng)用到RecyclerView中即可。
以下是一個示例代碼,演示如何創(chuàng)建一個自定義的ItemDecoration類來繪制分隔線:
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable divider;
public DividerItemDecoration(Context context) {
divider = ContextCompat.getDrawable(context, R.drawable.divider);
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + divider.getIntrinsicHeight();
divider.setBounds(left, top, right, bottom);
divider.draw(c);
}
}
}
然后在RecyclerView中應(yīng)用該ItemDecoration類:
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.addItemDecoration(new DividerItemDecoration(this));
這樣就可以在RecyclerView中顯示分隔線了。您可以根據(jù)自己的需求和創(chuàng)意,定制不同的ItemDecoration類來改變列表項的顯示效果。