RecyclerView分割线
时间: 2023-09-17 11:12:42 浏览: 111
recyclerView的分割线
RecyclerView分割线可以通过设置ItemDecoration来实现。下面是一个示例代码:
首先,创建一个分割线的类,继承自RecyclerView.ItemDecoration:
```java
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public DividerItemDecoration(Context context) {
// 获取系统默认的分割线Drawable
TypedArray styledAttributes = context.obtainStyledAttributes(new int[]{android.R.attr.listDivider});
mDivider = styledAttributes.getDrawable(0);
styledAttributes.recycle();
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
```
然后,在使用RecyclerView的地方,添加分割线:
```java
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.addItemDecoration(new DividerItemDecoration(this));
```
这样就可以在RecyclerView的每个Item之间添加一个默认的分割线了。如果需要自定义分割线的样式,可以修改DividerItemDecoration类中的绘制逻辑或者使用其他Drawable替代mDivider。
阅读全文