一般我们在Android画虚线有两种方式 1.布局里面画虚线: 在drawable里面创建一个dotted_line_view.xml文件,里面内容如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke android:color="@color/colorAccent" android:width="1dp" android:dashGap="4dp" android:dashWidth="4dp"/>
<size android:height="1dp"/>
</shape>
复制代码
在布局中添加控件:
<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:background="@drawable/dotted_line_view"
android:layerType="software"></View>
复制代码
这里需要注意的是,如果是用的这种布局格式的最好添加 android:layerType="software"
可以防止布局中虚线变成实线的问题,在Android4.0以上的系统可能会有这个问题出现,同时android:layout_height="10dp"
高度不要太小,否则可能显示不出虚线。
2.代码方式,自定义控件画虚线,代码如下:
public class DottedLineView extends View {
private Paint mPaint;
private int mWidth;
private Path mPath;
private int mLineColor;
/**
* 虚线
*/
private float mLineStrokeHeight;
/**
* 每格虚线的宽
*/
private int mDottedLineWidth;
public DottedLineView(Context context) {
this(context, null);
}
public DottedLineView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public DottedLineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
initStyle();
}
private void init(AttributeSet attrs) {
TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.DottedLineView);
mLineColor = array.getColor(R.styleable.DottedLineView_line_color, Color.BLACK);
mLineStrokeHeight = array.getDimension(R.styleable.DottedLineView_line_stroke_height, dp2px(getContext(), 1));
mDottedLineWidth = (int) array.getDimension(R.styleable.DottedLineView_dotted_line_width, 20);
array.recycle();
}
private void initStyle() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(mLineStrokeHeight);
mPaint.setColor(mLineColor);
PathEffect pathEffect = new DashPathEffect(new float[]{mDottedLineWidth, mDottedLineWidth}, 1);
mPaint.setPathEffect(pathEffect);
mPath = new Path();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPath.moveTo(0, 0);
mPath.lineTo(mWidth, 0);
canvas.drawPath(mPath, mPaint);
}
/**
* dp转px
*/
public int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getApplicationContext().getResources().getDisplayMetrics());
}
}
复制代码
在value文件夹里面新建attr.xml文件,里面内容如下:
<declare-styleable name="DottedLineView">
<attr name="line_stroke_height" format="dimension"/>
<attr name="line_color" format="color"/>
<attr name="dotted_line_width" format="dimension"/>
</declare-styleable>
复制代码
在布局xml中使用如下:
<com.lift.ajun.testapplication.DottedLineView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:line_stroke_height="2dp"
android:layout_marginTop="50dp"
app:line_color="@color/colorAccent"/>
复制代码