控件有很多屬性,如android:id、android:layout_width、android:layout_height等,但是這些屬性都是系統自帶的屬性。使用attrs.xml文件,可以自己定義屬性。本文在Android自定義控件的基礎上,用attrs.xml文件自己定義了屬性。
首先,在values文件夾下,新建一個attrs.xml文件,文件內容如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CustomView"> <attr name="tColor" format="color" /> <attr name="tSize" format="dimension" /> </declare-styleable> </resources>
其中,<declare-styleable name="CustomView">表明樣式名稱為CustomView,下面包含了兩個自定義屬性tColor和tSize,其中tColor是顏色(color)類的屬性,tSize是尺寸(dimension)類的屬性。
主窗體的布局文件如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:test="http://schemas.android.com/apk/res/com.hzhi.customview" 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.hzhi.customview.CustomView android:id="@+id/cusView" android:layout_width="wrap_content" android:layout_height="wrap_content" test:tColor="#00FFFF" test:tSize="30dp" > </com.hzhi.customview.CustomView> </RelativeLayout>
定義了xmlns:test="http://schemas.android.com/apk/res/com.hzhi.customview"(其中com.hzhi.customview是包名),在控件屬性中就可以增加test:tColor和test:tSize兩個屬性。
CustomView.java的構造函數:
// 構造函數 public CustomView(Context context, AttributeSet attrs) { super(context, attrs); // 獲得TypedArray TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView); // 獲得attrs.xml里面的屬性值,格式為:名稱_屬性名,后面是默認值 int tColor = a.getColor(R.styleable.CustomView_tColor, Color.GREEN); float tSize = a.getDimension(R.styleable.CustomView_tSize, 35); p.setColor(tColor); p.setTextSize(tSize); // 返回一個綁定資源結束的信號給資源 a.recycle(); }
首先從R.styleable.CustomView獲得了TypedArray變量,再用getColor(),getDimension()等方法獲取相應的屬性值,屬性格式為“樣式名_屬性名”,屬性后面的參數是默認值。獲得屬性值以后,就可以應用這些屬性值。recycle()方法用於返回信號給資源(不懂什么意思)。
運行結果如下: