0918Android基础自定义属性

本文介绍如何在Android中创建自定义View属性,包括定义XML属性文件、在布局文件中声明和使用自定义命名空间、调用自定义属性及在View中获取并应用这些属性的方法。
自定义属性
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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值