自定义属性
1
在Value中新建一个xml文件,添加要自定义使用的属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myView" >
<attr name="myBackground" format="reference"/>
<attr name="myStrokeWidth" format="reference|dimension"/>
</declare-styleable>
</resources>
2
在布局文件中声明
xmlns:myview="http://schemas.android.com/apk/res-auto"
3
在布局文件中调用
myview:myBackground="@mipmap/nurse"
myview:myStrokeWidth="100dp"
4
在View中设置
mPaintDst = new Paint();
// 返回一个TypeArray,其中包含持有其列在ATTRS的样式资源中定义的值。
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.myView);
// 获得其中一个的属性,布局文件中设置的话就能获得具体的属性,将drawable类型强转为bitmap类型
BitmapDrawable dra = (BitmapDrawable) a.getDrawable(R.styleable.myView_myBackground);
Log.d("drawable", "得到背景图片 ");
if (dra != null) {
Log.d("drawable", "drawable :" + dra.getIntrinsicWidth());
mBitmapBackground = dra.getBitmap();//获得图片
} else {
// 设置默认值
mBitmapBackground = BitmapFactory.decodeResource(getResources(), R.mipmap.dog);
}
// 将传进来的dp转化为px,第二个数为默认值
int paintWidth=a.getDimensionPixelOffset(R.styleable.myView_myStrokeWidth,30);
mPaintDst.setStrokeWidth(paintWidth);