在RecyclerView项之间设置自定义分隔线

时间:2019-04-29 19:54:52

标签: java android xml android-recyclerview

我正在尝试在Recyclerview个项目之间设置自定义分隔线:

enter image description here

XML:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">

    <stroke
        android:width="1dp"
        android:color="#000"
        android:dashWidth="20px"
        android:dashGap="50px" />
</shape>

Java:

DividerItemDecoration itemDecorator = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
itemDecorator.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.dashedline));
上面的

代码无法代替虚线显示,我得到了

enter image description here

1 个答案:

答案 0 :(得分:1)

DividerItemDecoration假定您提供的可绘制对象是一个实心矩形,并且讨厌地忽略了您的行XML定义。我发现一种解决方法是手动创建平铺的BitmapDrawable,例如:

    // get pixel count for 1 dip
    float dip1 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1f, getContext().getResources().getDisplayMetrics());

    // create a bitmap to draw our dash
    Bitmap bitmap = Bitmap.createBitmap((int)(15f * dip1) , (int)dip1, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();

    // fill the bitmap with the background colour of the list items
    canvas.drawColor(listItemBackgroundColour);

    // create a dash effect dash with = 10 dip, dash gap = 5 dip
    paint.setPathEffect(new DashPathEffect(new float [] { 10f * dip1, 5f * dip1 }, 0));

    // draw a single pixel wide line across the bitmap
    paint.setStrokeWidth(dip1);
    paint.setColor(lineColour);
    paint.setStyle(Paint.Style.STROKE);
    canvas.drawLine(0f, dip1 / 2f, 15f * dip1, dip1 / 2f, paint);

    // now create a tiled drawable using the bitmap
    BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
    drawable.setTileModeX(Shader.TileMode.REPEAT);

    // pass the drawable to the item decorator
    DividerItemDecoration itemDecorator = new DividerItemDecoration(getContext(), layoutManager.getOrientation());
    itemDecorator.setDrawable(drawable);
    addItemDecoration(itemDecorator);

不像XML形状资源定义那么整洁,但是可以解决问题。

请注意,您需要知道回收站项目背景的颜色才能在虚线中混合,否则您将获得主题背景颜色(通过虚线的空白显示)。

希望这会有所帮助。