例子sdk路径C:\Users\TANG\AppData\Local\Android\Sdk\platforms\android-30\data\res\values
attrs.xml 中参考属性 同时在as中增加同名xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="godvAtt">
<attr name="gv_title" format="string" />
<attr name="gv_size" format="dimension" />
<attr name="gv_src" format="reference" />
</declare-styleable>
</resources>
GodvView.java
package com.example.godvlean;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
public class GodvView extends View {
private float gvSize;
private int gvNum;
private Drawable gvSrc;
private String gvTitle;
private Paint paint;
public GodvView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//通过控件方式来获取
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.godvAtt);
gvSize = typedArray.getDimension(R.styleable.godvAtt_gv_size, 0f);
gvSrc = typedArray.getDrawable(R.styleable.godvAtt_gv_src);
gvTitle = typedArray.getString(R.styleable.godvAtt_gv_title);
gvNum = typedArray.getInt(R.styleable.godvAtt_gv_text_num,0);
typedArray.recycle(); // 因为源码中是进行回收的
paint = new Paint();
paint.setColor(Color.BLUE); //颜色
paint.setTextSize(gvSize);//字体大小
paint.setTypeface(Typeface.DEFAULT_BOLD);//粗体字
paint.setAntiAlias(true);//消除锯齿
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//画绿色背景
canvas.drawColor(Color.GREEN);
//画文本
canvas.drawText(gvTitle, 10, 120, paint);
//画图
gvSrc.setBounds(20,20,100,100);
gvSrc.draw(canvas);
}
}
xml
<com.example.godvlean.GodvView
android:layout_width="match_parent"
android:layout_height="match_parent"
godv:gv_title="we1less"
godv:gv_size="58dp"
godv:gv_src="@mipmap/godv"
godv:gv_text_num="2"/>