您的位置:首页 > 其它

自定义控件的属性(attr.xml,TypedArray)的使用

2016-05-16 12:54 183 查看
自定义控件的属性需要三步:

第一:在res/values文件下定义一个attrs.xml文件,代码如下

<?xml version="1.0" encoding="utf-8"?>

<resources>

<declare-styleable name="CircleView">

<attr name="border_width" format="dimension"></attr>

<attr name="border_color" format="color"></attr>

</declare-styleable>

</resources>

二、在布局xml中如下使用该属性:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

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

xmlns:apple="http://schemas.android.com/apk/res/com.example.name"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity" >

<com.example.name.CirCleView

android:id="@+id/cv"

android:layout_width="200dp"

android:layout_height="200dp"

android:layout_centerInParent="true"

android:src="@drawable/ic_launcher"

apple:border_color="#ff00ff00"

apple:border_width="2dp" >

</com.example.name.CirCleView>

</RelativeLayout>

三、在自定义组件中,可以如下获得xml中定义的值:

TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.CircleView);

borderWidth = t.getDimensionPixelSize(R.styleable.CircleView_border_width, 0);

borderColor = t.getColor(R.styleable.CircleView_border_color, Color.WHITE);

t.recycle();

这几部即可完成对自定义属性的使用。

总结:

首先来看看attrs.xml文件。该文件是定义属性名和格式的地方,需要用<declare-styleable name="CircleView"></declare-styleable>包围所有属性。其中name为该属性集的名字,主要用途是标识该属性集。那在什么地方会用到呢?主要是在下面的第三步。看到没?在获取某属性标识时,用到"R.styleable.CircleView_buttonNum",很显然,他在每个属性前面都加了"CircleView_"。如果该属性可同时传两种不同的属性,则可以用“|”分割开即可。

TypedArray类 包含函数

obtainStyledAt tributes(AttributeSet,
int[], int, int)

或者 %29]obtainAttributes(AttributeSet, int[])检索的数组值。

其中

set:现在检索的属性值;

attrs:制定的检索的属性值

然后就可以用“t”的各种方法来获取相应的属性值了。这里需要注意的是,如果使用的方法和获取值的类型不对的话,则会返回默认值。因此,如果一个属性是带两个及以上不用类型的属性,需要做多次判断,知道读取完毕后才能判断应该赋予何值。当然,在取完值的时候别忘了回收资源哦!在执行完之后,一定要确保调用 recycle()函数 。用于检索从这个结构对应于给定的属性位置到obtainStyledAttributes中的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: