阅读量:0
要通过ItemDecoration改变列表项的显示效果,可以创建一个自定义的ItemDecoration类,并重写其onDraw()和onDrawOver()方法来实现想要的效果。例如,可以在onDraw()方法中绘制分隔线或背景色,或者在onDrawOver()方法中绘制悬浮的标签等。然后将该ItemDecoration类应用到RecyclerView中即可。
以下是一个示例代码,演示如何创建一个自定义的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中应用该ItemDecoration类:
RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.addItemDecoration(new DividerItemDecoration(this));
这样就可以在RecyclerView中显示分隔线了。您可以根据自己的需求和创意,定制不同的ItemDecoration类来改变列表项的显示效果。