阅读量:0
要自定义Android的ItemDecoration,可以创建一个继承自RecyclerView.ItemDecoration的自定义类,并实现其中的方法来自定义item的绘制。
下面是一个示例代码,可以自定义ItemDecoration来实现分割线的效果:
public class CustomItemDecoration extends RecyclerView.ItemDecoration { private int dividerHeight; public CustomItemDecoration(int dividerHeight) { this.dividerHeight = dividerHeight; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.set(0, 0, 0, dividerHeight); } @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 + dividerHeight; Paint paint = new Paint(); paint.setColor(Color.RED); c.drawRect(left, top, right, bottom, paint); } } }
然后在RecyclerView中设置这个自定义的ItemDecoration:
RecyclerView recyclerView = findViewById(R.id.recyclerView); recyclerView.addItemDecoration(new CustomItemDecoration(10));
这样就可以实现自定义的分割线效果。通过自定义ItemDecoration,可以实现各种不同的item样式和效果,例如间隔、分割线、边距等。