android之TypedArray

一、在res/values文件下定義一個attrs.xml文件,代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToolBar">
<attr name="buttonNum" format="integer"/>
<attr name="itemBackground" format="reference|color"/>
</declare-styleable>
</resources>

二、在佈局xml中如下使用該屬性:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<cn.zzm.toolbar.ToolBar android:id="@+id/gridview_toolbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/control_bar"
android:gravity="center"
toolbar:buttonNum="5"
toolbar:itemBackground="@drawable/control_bar_item_bg"/>
</RelativeLayout>
</resources>

三、在自定義組件中,可以如下獲得xml中定義的值:

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar);
buttonNum = a.getInt(R.styleable.ToolBar_buttonNum, 5);
itemBg = a.getResourceId(R.styleable.ToolBar_itemBackground, -1);

a.recycle();
------------------------------------------------------------------------------------------------

好了,基本用法已經講完了,現在來看看一些注意點和知識點吧。

首先來看看attrs.xml文件。

該文件是定義屬性名和格式的地方,需要用<declare-styleable name="ToolBar"></declare-styleable>包圍所有屬性。其中name爲該屬性集的名字,主要用途是標識該屬性集。那在什麼地方會用到呢?主要是在第三步。看到沒?在獲取某屬性標識時,用到"R.styleable.ToolBar_buttonNum",很顯然,他在每個屬性前面都加了"ToolBar_"。

在來看看各種屬性都有些什麼類型吧:string , integer , dimension , reference , color , enum.

前面幾種的聲明方式都是一致的,例如:<attr name="buttonNum" format="integer"/>。
只有enum是不同的,用法舉例:

<attr name="testEnum">
<enum name="fill_parent" value="-1"/>
<enum name="wrap_content" value="-2"/>
</attr>

如果該屬性可同時傳兩種不同的屬性,則可以用“|”分割開即可。



讓我們再來看看佈局xml中需要注意的事項。

首先得聲明一下:xmlns:toolbar=http://schemas.android.com/apk/res/cn.zzm.toolbar
注意,“toolbar”可以換成其他的任何名字,後面的url地址必須最後一部分必須用上自定義組件的包名。
自定義屬性了,在屬性名前加上“toolbar”即可。



最後來看看java代碼中的注意事項。

在自定義組件的構造函數中,用

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar);

來獲得對屬性集的引用,然後就可以用“a”的各種方法來獲取相應的屬性值了。這裏需要注意的是,
如果使用的方法和獲取值的類型不對的話,則會返回默認值。因此,如果一個屬性是帶兩個及以上不用類型的屬性,
需要做多次判斷,知道讀取完畢後才能判斷應該賦予何值。當然,在取完值的時候別忘了回收資源哦!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章