要自定義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樣式和效果,例如間隔、分割線、邊距等。