自定義屬性首先需要在values目錄下attr.xml下定義,新項(xiàng)目可能沒(méi)有紧卒,需要自己創(chuàng)建即可
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TestView01">
<attr name="LColor" format="color"></attr>
<attr name="RColor" format="color"></attr>
<attr name="TxtColor" format="color"></attr>
<attr name="Kuan" format="dimension"></attr>
</declare-styleable>
</resources>
自定義屬性設(shè)置完畢既可以直接在xml布局里面添加屬性
然后自定義view里面獲取屬性值
public class TestView01 extends View {
private Paint paint;
private int LColor=Color.RED; //左圈顏色
private int RColor=Color.BLUE; //右圈顏色
private int TxtColor=Color.BLACK; //文本顏色
private int kuan=10; //圓弧寬度
public TestView01(Context context) {
this(context,null);
}
public TestView01(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public TestView01(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr,0);
}
public TestView01(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
TypedArray butes = context.obtainStyledAttributes(attrs,R.styleable.TestView01);
LColor = butes.getColor(R.styleable.TestView01_LColor, LColor);
RColor = butes.getColor(R.styleable.TestView01_RColor, RColor);
TxtColor = butes.getColor(R.styleable.TestView01_TxtColor, TxtColor);
kuan = butes.getColor(R.styleable.TestView01_Kuan,kuan);
}
}
判斷測(cè)量模式侥衬,通過(guò)畫(huà)筆測(cè)量文本內(nèi)容大小,重新設(shè)置大小
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
/*MeasureSpec.UNSPECIFIED 不確定值跑芳,鋪滿
MeasureSpec.AT_MOST 最大值轴总,包裹內(nèi)容
MeasureSpec.EXACTLY 完全準(zhǔn)確值*/
int modeW = MeasureSpec.getMode(widthMeasureSpec); //獲取測(cè)量模式
int modeH = MeasureSpec.getMode(heightMeasureSpec);
if(modeW==MeasureSpec.AT_MOST){ //如果模式等于wrap_content 需要手動(dòng)賦值
Rect bounds=new Rect();
paint.getTextBounds("內(nèi)容",0,"內(nèi)容".length(),bounds); //通過(guò)畫(huà)筆獲取文本的Rect大小
bounds.width();//獲得的寬
bounds.height();//獲得的高
}
setMeasuredDimension(widthMeasureSpec,heightMeasureSpec); // 重新設(shè)置大小
}
計(jì)算文本基線
paint = new Paint();
paint.setAntiAlias(true); //抗鋸齒打開(kāi)
paint.setColor(Color.BLACK); //設(shè)置畫(huà)筆的顏色
paint.setTextSize(100); //設(shè)置畫(huà)筆的大小
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt(); //獲取文字排版信息
int dy=(fontMetricsInt.bottom-fontMetricsInt.top)-fontMetricsInt.bottom;
int baseLins = getHeight() / 2 + dy; //獲得文本基線
canvas.drawText("內(nèi)容",0,getHeight()/2+baseLins,paint);
//invalidate(); 重新繪制
}