http://marshal.easymorse.com/archives/3068
首先要建立變數,建立了個values/attrs.xml檔案,檔案名稱任意,但是要在values目錄下:
<?xml version="1.0" encoding="utf-8"?><br /><resources><br /> <declare-styleable name="button"><br /> <attr name="textSize" format="dimension" /><br /> </declare-styleable><br /></resources>
根標籤要是resources,定義的變數要有個名字,declare-styleable
name="button">,這裡定義名稱為button。在這個名稱裡,可以有多個自訂屬性。定義了個名為textSize的屬性,格式是
dimension,這個format指定了textSize屬性的類型,只能用於定義字型大小。
在布局檔案中通過自訂屬性賦值:
<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> xmlns:myapp="http://schemas.android.com/apk/res/com.easymorse.textbutton"<br /> android:orientation="vertical" android:layout_width="fill_parent"<br /> android:layout_height="fill_parent" android:background="@drawable/background_color"><br /> <LinearLayout android:layout_width="fill_parent"<br /> android:layout_height="10dip" /><br /> <LinearLayout android:layout_width="fill_parent"<br /> android:layout_height="40dip"><br /> <com.easymorse.textbutton.TextButton<br /> android:layout_width="fill_parent" android:layout_height="fill_parent"<br /> android:layout_weight="1" android:text="電影"<br /> android:gravity="center_vertical|center_horizontal"<br /> android:background="@drawable/button" android:focusable="true"<br /> android:clickable="true" myapp:textSize="20sp" />
這裡在根標籤中增加了:
xmlns:myapp=http://schemas.android.com/apk/res/com.easymorse.textbutton
聲明了myapp這個名字空間,myapp是任意的名稱,自己可以隨便起名,後面的:
http://schemas.android.com/apk/res/
是固定的。再後面接的是應用的包名。
在下面自訂按鈕中的:myapp:textSize,就是使用<attr name="textSize"這個變數了,給變數賦值。
還需要一個過程,就是在程式中擷取到這個賦值:
public TextButton(final Context context, AttributeSet attrs) {<br /> this(context, attrs, 0);<br /> TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.button);<br /> this.setTextSize(typedArray.getDimension(R.styleable.button_textSize, 15));<br /> typedArray.recycle();
其中,TypedArray執行個體是個屬性的容器,context.obtainStyledAttributes()方法返回得到。
AttributeSet是節點的屬性集合,在本例中是<com.easymorse.textbutton.TextButton節點中的屬性集合。這句話:
typedArray.getDimension(R.styleable.button_textSize,15)
將擷取自訂textSize的值,如果沒有,則使用預設的值,15。
最後別忘記調用:
typedArray.recycle();
作用是:
Give back a previously retrieved StyledAttributes, for later re-use.
這裡的自訂屬性的format,可以有很多種:
- reference
- string
- color
- dimension
- boolean
- integer
- float
- fraction
- enum
- flag