我们在布局文件中,会对一些控件设置一些属性,这些属性都是定义好的,使用的时候设定该属性的,否则就是用默认值。主要看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>