我要画一条虚线。我现在用这个来画实线:
LinearLayout divider = new LinearLayout( this );
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 2 );
divider.setLayoutParams( params );
divider.setBackgroundColor( getResources().getColor( R.color.grey ) );
我需要这样的东西,但不是实心的,而是虚线的。我想避免在透明布局和固体布局之间交替制作数百个布局。
唯一对我有用的方法,我认为这是最简单的方法,就是使用Path和一个paint对象,就像这样:
Paint paintDash = new Paint();
paintDash.setARGB(255, 0, 0, 0);
paintDash.setStyle(Paint.Style.STROKE);
paintDash.setPathEffect(new DashPathEffect(new float[]{10f,10f}, 0));
paintDash.setStrokeWidth(2);
Path pathDashLine = new Path();
然后onDraw():(重要调用重置,如果你改变这些点之间的onDraw调用,导致路径保存所有的移动)
pathDashLine.reset();
pathDashLine.moveTo(porigenX, porigenY);
pathDashLine.lineTo(cursorX,cursorY);
c.drawPath(pathDashLine, paintDash);
这些答案对我都没用。大多数答案都给出了一个半透明的边框。为了避免这种情况,您需要再次用另一个具有您喜欢的颜色的容器包装您的容器。这里有一个例子:
这就是它的样子
dashed_border_layout.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/black"
android:background="@drawable/dashed_border_out">
<LinearLayout
android:layout_width="150dp"
android:layout_height="50dp"
android:padding="5dp"
android:background="@drawable/dashed_border_in"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Dashed Container"
android:textSize="16sp" />
</LinearLayout>
dashed_border_in.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<corners android:radius="10dp" />
<solid android:color="#ffffff" />
<stroke
android:dashGap="5dp"
android:dashWidth="5dp"
android:width="3dp"
android:color="#0000FF" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
</shape>
</item>
dashed_border_out.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<corners android:radius="12dp" />
</shape>
</item>