【问题标题】:Set custom divider line between RecyclerView items在 RecyclerView 项目之间设置自定义分隔线
【发布时间】:2019-04-29 19:54:52
【问题描述】:

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

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));

上面的代码不起作用,而不是虚线我明白了:

【问题讨论】:

    标签: java android xml android-recyclerview


    【解决方案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 形状资源定义那样简洁,但它可以解决问题。

    请注意,您需要知道回收站物品的背景颜色才能融入虚线,否则您将通过虚线的间隙获得主题背景颜色。

    希望这会有所帮助。

    【讨论】:

    • 修改解决方案以使用倾角值而不是绝对像素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 2016-03-09
    相关资源
    最近更新 更多