ITDHW 2014-06-16
一、在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();
<declare-styleablename="ToolBar"></declare-styleable>包围所有属性:
1\其中name为该属性集的名字,主要用途是标识该属性集
2\"R.styleable.ToolBar_buttonNum",在每个属性前面都加了"ToolBar_"
[string,integer,dimension,reference,color,enum]
转自:
http://linapex.blog.163.com/blog/static/189237516201251553056418/