要實現Android中列表項間的分隔線,可以通過自定義ItemDecoration來實現。以下是一個簡單的示例:
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable divider;
public DividerItemDecoration(Context context, int resId) {
divider = ContextCompat.getDrawable(context, resId);
}
@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() - 1; 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 recyclerView = findViewById(R.id.recyclerView);
recyclerView.addItemDecoration(new DividerItemDecoration(this, R.drawable.divider));
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="1dp"/>
<solid android:color="@color/divider_color"/>
</shape>
通過以上步驟,就可以實現在RecyclerView中為列表項添加分隔線了。如果想要自定義分隔線的樣式,可以修改DividerItemDecoration中的onDraw方法和divider.xml中的shape屬性。