正确的方法是为RecyclerView定义ItemDecoration,如下所示
SimpleDividerItemDecoration.java
public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public SimpleDividerItemDecoration(Context context) {
mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);
}
@Override
public void onDrawOver(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);
}
}
}
或者如果你正在使用 Kotlin:
SimpleDividerItemDecoration.kt
class SimpleDividerItemDecoration(context: Context, @DrawableRes dividerRes: Int) : ItemDecoration() {
private val mDivider: Drawable = ContextCompat.getDrawable(context, dividerRes)!!
override fun onDrawOver(c: Canvas, parent: RecyclerView) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0 until childCount) {
val child: View = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top: Int = child.bottom + params.bottomMargin
val bottom = top + mDivider.intrinsicHeight
mDivider.setBounds(left, top, right, bottom)
mDivider.draw(c)
}
}
}
line_divider.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="1dp"
android:height="1dp" />
<solid android:color="@color/dark_gray" />
</shape>
最后设置成这样
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this))
编辑
正如@Alan S.所指出的那样。
context.getResources().getDrawable(R.drawable.line_divider)
已经过时,您可以使用
ContextCompat.getDrawable(context,R.drawable.line_divider)