做Android佈局是件很享受的事,這得益於他良好的xml方式。使用xml可以快速有效的爲軟件定義界面。可是有時候我們總感覺官方定義的一些基本組件不夠用,自定義組件就不可避免了。那麼如何才能做到像官方提供的那些組件一樣用xml來定義他的屬性呢?現在我們就來討論一下他的用法。
一、在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>
三、在自定義組件中,可以如下獲得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();