Android原有的屬性可能不能滿足我們現在要做的事,畢竟有些人就是會天馬行空的想出一些Android不會做的東西。今天就簡單的寫下怎樣為自訂控制項自訂屬性,看這種描述有點暈,轉過來就是控制項和屬性都是自訂的吧。哈~
上面是運行介面,有兩個自訂的Button,主要是用來區分。
首先在res/values/
目錄下建立attrs.xml檔案,用來自訂屬性
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="MyCustomWidget"> <attr name="myText" format="string"/> <attr name="isEnable" format="boolean"/> </declare-styleable></resources>
標籤declare-styleable的name值為可以通過這個值擷取相關屬性,這表明把這些屬性賦給自訂的控制項。
下面在MyCustomWidget.java的建構函式總從xml屬性中讀取到設定的值,利用獲得的值就可以做自己的事了,代碼如下:
package nbe.sense7.vinci.custom.xmlattrs;import android.content.Context;import android.content.res.TypedArray;import android.util.AttributeSet;import android.widget.Button;public class CustomWedgit extends Button { public CustomWedgit(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomWidget); final int indexCount = a.getIndexCount(); for (int i = 0; i < indexCount; ++i) { int attr = a.getIndex(i); switch (attr) { case R.styleable.MyCustomWidget_myText: //擷取myText屬性值 String myText = a.getString(attr); //得到值後就可以按你想要的使用了,我這裡是給Button設定按鈕顯示文字 CustomWedgit.this.setText(myText); break; case R.styleable.MyCustomWidget_isEnable: boolean isEnable = a.getBoolean(attr, false); // 這裡利用布爾屬性值做自己想做的 break; } } a.recycle(); }}
最後把自訂的屬性加入到layout裡面,main.xml:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:vinci="http://schemas.android.com/apk/res/nbe.sense7.vinci.custom.xmlattrs" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <nbe.sense7.vinci.custom.xmlattrs.CustomWedgit android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button內建text屬性設定的值" /> <nbe.sense7.vinci.custom.xmlattrs.CustomWedgit android:layout_width="fill_parent" android:layout_height="wrap_content" vinci:myText="Button自訂myText屬性設定的值" /></LinearLayout>
最重要的一點是別忘了要加入上面深色的一行,xmlns:後面可以加入自訂的名字,我的是vinici,對於引號裡面的值應該是xmlns:vinci="http://schemas.android.com/apk/res/你的包名"。
OK~寫完手工!!