gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:12:04 28 4
gpt4 key购买 nike

我正在尝试在 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

最佳答案

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

请注意,您需要知道回收站项目背景的颜色才能混合到虚线中,否则您将通过虚线的间隙显示主题背景颜色。

希望这对您有所帮助。

关于java - 在 RecyclerView 项目之间设置自定义分隔线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55909974/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com