我們在佈局文件中,會對一些控件設置一些屬性,這些屬性都是定義好的,使用的時候設定該屬性的,否則就是用默認值。主要看framework下是如何定義屬性的及使用。
一、屬性定義,在values中創建一個attrs.xml文件,然後如下幾種格式定義屬性、
1、一般格式
<attr name = "textColor" format = "color" />
其中Format值有如下幾種
"reference" //引用
"color" //顏色
"boolean" //布爾值
"dimension" //尺寸值
"float" //浮點值
"integer" //整型值
"string" //字符串
"fraction" //百分數,比如200%
屬性定義可以指定多種類型,如
<attrname="textColor" format="reference|color" />
2、枚舉類型格式
<attrname="streamType">
<enum name="voice"value="0" />
<enum name="system"value="1" />
<enum name="ring"value="2" />
<enum name="music"value="3" />
<enum name="alarm"value="4" />
</attr>
3、標誌位格式
<attr name="textStyle">
<flag name="normal"value="0" />
<flag name="bold"value="1" />
<flag name="italic"value="2" />
</attr>
二、在定義的組件的構造函數中進行設置
public CheckBoxPreference(Context context,AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a =context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.CheckBoxPreference,defStyle, 0);
setSummaryOn(a.getString(com.android.internal.R.styleable.CheckBoxPreference_summaryOn));
setSummaryOff(a.getString(com.android.internal.R.styleable.CheckBoxPreference_summaryOff));
setDisableDependentsState(a.getBoolean(
com.android.internal.R.styleable.CheckBoxPreference_disableDependentsState,false));
a.recycle();
}
三、XML文件中使用
定義xmlns:android=http://schemas.android.com/apk/res/android,這是一個XML命名空間,告訴Android開發工具你準備使用Android命名空間裏的一些通用屬性。
在所有AndroidXML設計文件中最外層的標記必須使用這個樹形。有了它,你就可以alt+/作爲提示,有哪些字段可以使用。
然後可以設置各個屬性,例如:
<VolumePreference
android:key="volume_setting"
android:title="@string/alarm_volume_title"
android:dialogTitle="@string/alarm_volume_title"
android:streamType="alarm"/>
四、自定義屬性
在values目錄下創建attrs.xml文件
<?xmlversion="1.0" encoding="utf-8"?>
<resources>
<declare-styleablename="CustomView">
<attr name="textColor"format="color" />
<attr name="textSize"format="dimension" />
</declare-styleable>
</resources>
創建自定義view,在構造函數中對屬性進行設置
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CustomView);
int textColor = a.getColor(R.styleable.CustomView_textColor,0xFFFFFF00);
float textSize = a.getDimension(R.styleable.CustomView_textSize,20);
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
a.recycle();
}
在佈局文件中使用屬性,如果沒有設定就是用默認的
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/apk/res/com.example.customattr"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.customattr.CustomView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textSize="50px"
test:textColor="#000000"/>
</LinearLayout>