自己定義的佈局,需要自己自定義view,通常繼承View然後重寫構造方法以及onDraw等函數。同時,我們也可以自定義屬性。步驟如下:
- 在項目文件res/value下面創建一個attr.xml文件,該文件包含若干個attr的集合,例如:
<Resources>
<declare-styleable name="MyView">
<attr name="myTextSize"format="dimension"/>
<attr name="myColor"format="color"/>
</declare-styleable>
</Resources>
其中resource是根標籤,可以在裏面定義若干個declare-styleable,<declare-styleable name=”myView“> 中name定義了變量名稱,下面可以再定義多個屬性,針對<attr name=”myTextSize” format=”dimension”/>來說,其屬性的名稱爲”myTextSize“,format指定了該屬性類型爲dimension,只能表示字體的大小。
Format還可以指定其他的類型,比8如:
Reference 表示引用,參考某一資源的ID。
String 表示字符串
Color 表示顏色值
Dimension 表示尺寸值
Boolean表示布爾值
Integer 表示整型值
Float 表示浮點值
Fraction 表示百分數
Enum 表示枚舉值
Flag 表示位運算
2.在使用該自定義view的佈局文件中加入如下一行:
xmlns :app=”http://schemas.android.com/apk/res/com...“ 注意(後面的com.什麼爲activity的包名)
3.在自定義view的代碼中引入自定義屬性。修改構造函數
Context通過調用obtainStyledAttributes方法來獲取一個TypeArray,然後又該TypeArray來對屬性進行設置,
obtainStyledAttributes方法有三個,我們常用的是有一個參數的obtainStyledAttributes(int[] attrs),其參數直接styleable中獲得。
TypedArray a = context.obtainStyledAttributes(attrs ,R.Styleable.MyView);
調用結束後務必調用recycle()方法。否則這次的設定會影響下次的使用。
注意:屬性定義時可以指定多種類型值:
1.屬性定義:
<declare-styleable name=”名稱”>
<attr name=”background” format=”reference|color”/>
</declare-styleable>
2.屬性使用:
<ImageView
android:layout_width = “42dip”
android:layout_height=”42dip”
android:background=”@drawable/圖片id|顏色#。。。”/>