本文主要是介绍Android 自定义垂直虚线控件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
开发中遇到垂直虚线作为分割线,本以为使用shape可以解决,没想到shape实现的只有水平方面的虚线没有垂直方向,无奈只能自己写一个控件。
为了以后使用方便,将设置控件的样式提到外部实现。需要的同学也可以拿去使用
1.在attrs.xml文件中添加使用方法
<declare-styleable name="LineDashView"><!--虚线颜色--><attr name="color" format="color"/><!--虚线宽度--><attr name="dashWidth" format="dimension"/><!--虚线间隔--><attr name="dashGap" format="dimension"/><!--虚线方向 垂直还是水平--><attr name="line_orientation" format="integer"><!--水平虚线--><enum name="horizontal" value="0" /><!--垂直虚线--><enum name="vertical" value="1" /></attr></declare-styleable>
2.虚线view现实类
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;import com.zh.app.R;/*** Created by zhanghe on 2019/8/3.* 水平或者垂直虚线*/public class LineDashView extends View {private Paint mPaint;private int height;private int width;private Path mPath;private float orientation;public LineDashView(Context context) {this(context,null);}public LineDashView(Context context, @Nullable AttributeSet attrs) {this(context, attrs,0);}public LineDashView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LineDashView, defStyleAttr,0);float dashGap = a.getDimension(R.styleable.LineDashView_dashGap, 0);float dashWidth = a.getDimension(R.styleable.LineDashView_dashWidth, 0);orientation = a.getInt(R.styleable.LineDashView_line_orientation, 0);ColorStateList colorStateList = a.getColorStateList(R.styleable.LineDashView_color);a.recycle();colorStateList = colorStateList != null ? colorStateList : ColorStateList.valueOf(0xFF000000);int lineColor = colorStateList.getColorForState(getDrawableState(), 0);mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);mPaint.setColor(lineColor);mPaint.setStyle(Paint.Style.STROKE);DashPathEffect e = null;if (dashWidth > 0) {e = new DashPathEffect(new float[] { dashWidth, dashGap }, 0);}mPaint.setPathEffect(e);mPath = new Path();}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);width = MeasureSpec.getSize(widthMeasureSpec);height = MeasureSpec.getSize(heightMeasureSpec);mPaint.setStrokeWidth(width);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);if (orientation == 0){//水平mPath.moveTo(0,0);mPath.lineTo(width,0);}else if (orientation == 1){//垂直mPath.moveTo(0,0);mPath.lineTo(0,height);}canvas.drawPath(mPath,mPaint);}
}
3.xml布局文件使用方式
<com.zh.app.widget.LineDashViewandroid:layout_width="1dp"android:layout_height="match_parent"app:color="@color/white"app:line_orientation="vertical"app:dashGap="2dp"app:dashWidth="4dp"/>
这篇关于Android 自定义垂直虚线控件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!