自定义view属性 android,精通Android自定义View(四)自定义属性使用详解

1、简述

对于自定义属性,遵循以下几步,就可以实现:

自定义一个CustomView(extends View )类

编写values/attrs.xml,在其中编写styleable和item等标签元素

在布局文件中CustomView使用自定义的属性(注意namespace)

在CustomView的构造方法中通过TypedArray获取

2、自定义一个View

2.1 定义View

public class CustomView extends View {

//构造函数会在new的时候调用

public CustomView(Context context) {

this(context, null);

}

//在布局中使用

public CustomView(Context context, @Nullable AttributeSet attrs) {

this(context, attrs, 0);

}

//布局layout中调用,但是会有style

public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

}

}

2.2 编写values/attrs.xml

2.3 在布局文件中CustomView使用自定义的属性

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:text="1234" />

2.4 在CustomView的构造方法中通过TypedArray获取

//在布局中使用

public CustomView(Context context, @Nullable AttributeSet attrs) {

this(context, attrs, 0);

//获取自定义View中自定义属性的值

TypedArray lTypedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView);

String text = lTypedArray.getString(R.styleable.CustomView_text);

}

3、AttributeSet与TypedArray

AttributeSet可以获得布局文件中定义的所有属性的key和value

//获取属性的数量

int count = attrs.getAttributeCount();

for (int i = 0; i < count; i++) {

//属性名称

String attrName = attrs.getAttributeName(i);

//属性值

String attrVal = attrs.getAttributeValue(i);

Log.e("CustomView", "attrName = " + attrName + " , attrVal = " + attrVal);

}

TypedArray其实是用来简化我们的工作的,比如上例,如果布局中的属性的值是引用类型(比如:@dimen/dp100),如果使用AttributeSet去获得最终的像素值,那么需要第一步拿到id,第二步再去解析id。而TypedArray正是帮我们简化了这个过程

4、declare-styleable标签

declare-styleable标签 中的name属性定义的是这组自定义属性组的名称,也就是说在自定义控件中引用自定义属性时所有用的标识符

如这里定义的 为 CustomView

... ...

在引用的时候为

TypedArray lTypedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView);

5、定义可被多个自定义控件使用的属性

将属性定义在标签之外,这样自定义属性就可以被多个自定义控件使用了

本文同步分享在 博客“早起的年轻人”(CSDN)。

如有侵权,请联系 support@oschina.cn 删除。

本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值