Java 在RecyclerView项之间设置自定义分隔线
我试图在Java 在RecyclerView项之间设置自定义分隔线,java,android,xml,android-recyclerview,Java,Android,Xml,Android Recyclerview,我试图在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"
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>
DividerItemDecoration itemDecorator = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
itemDecorator.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.dashedline));
上面的代码不起作用,我得到的是虚线:
DividerItemDecoration
假设您提供的可绘制图形是实心矩形,令人恼火的是忽略了行XML定义。我发现的一个解决方法是手动创建平铺的位图绘制
,例如:
// 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形状资源定义那么简洁,但它确实做到了这一点
请注意,您需要知道回收项目的背景颜色,以融入虚线中,否则您将通过虚线中的间隙显示主题背景颜色
希望这能有所帮助。修改解决方案,使用倾斜值而不是绝对像素。