Android - 自定义带属性的控件
自定义带属性的控件:
format:
reference : 引用资源 体现的形式 @
color: 颜色值 #
enum: 枚举
dimension: 长度 dp
string: 字符串
float: 浮点型
integer: int 类型
fraction: 百分数
boolean: 布尔值
1) 声明属性:
value 文件下面创建一个xml
<declare-styleable name="MyView"> <attr name="icon" format="refrence" /> </declare-styleable>
2) 使用属性:
在自定义控件所在的布局文件里使用该属性, 根节点上添加新的命名空间
xmlns:view="http://schemas.android.com/apk/res/com.layla.mydroid"
在自定义控件里使用新属性 view:icon="@drawable/..."
3) 在自定义控件的类里获取属性并进行相关的操作
在带有AttributeSets的构造函数里获取
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomView); String title = array.getString(R.styleable.CustomView_title, title); array.recycle(); textView.setText(title);