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

avatar
作者
筋斗云
阅读量:0

要实现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属性。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!