温馨提示×

Android的ItemDecoration如何实现列表项间的分隔线

小樊
93
2024-08-15 10:02:38
栏目: 编程语言

要实现Android中列表项间的分隔线,可以通过自定义ItemDecoration来实现。以下是一个简单的示例:

  1. 首先创建一个自定义的ItemDecoration类,例如DividerItemDecoration:
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);
        }
    }
}
  1. 在RecyclerView的Adapter中设置DividerItemDecoration:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.addItemDecoration(new DividerItemDecoration(this, R.drawable.divider));
  1. 创建分隔线的drawable资源文件divider.xml:
<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属性。

0