自定义View的自定义属性,TypedArray的使用和命名空间

来源:互联网 发布:数据质量提升方案 编辑:程序博客网 时间:2024/05/20 21:19

自定义View自定义属性

我们平时使用的自定义View的一些属性可以通过代码的直接设置来实现,也可以定义在xml文件中来实现。

分为以下几步:

1. 需要在styles.xml文件中定义declare-styleable标签

 <declare-styleable name="MyViewStyle">        <attr name="sizes" format="integer" />        <attr name="colors" format="color" />        <attr name="a" format="dimension" />    </declare-styleable>

2. 在用到该自定义View的layout文件中定义命名空间 

xmlns:app="http://schemas.android.com/apk/res-auto"
        app只是一个名字,可以随意定义。
<com.example.wanghui12.asd.MyView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        app:sizes="50" />
使用的时候直接app:sizes=“”  就可以。

3. 简单使用

在自定义View的构造方法里
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyViewStyle);        int size = typedArray.getInteger(R.styleable.MyViewStyle_sizes, 10);        Log.i("whsqlitedatabase", "MyView: size=" + size);        typedArray.recycle();//记得recycle typedarray

4. 拓展,这只是简单的例子,实际使用中,可能会更复杂一点。。。

阅读全文
0 0