自定义属性步骤:
参数系统属性声明:adt-bundle-windows-x86\sdk\platforms\android-10\data\res\values\attrs.xml
一:声明所需要的属性
在res/values 目录中新建xml文件,名称一般为 attrs.xml
<resources>
<!-- 声明一个属性集合,名称,与拥有这些属性的类同名 -->
<declare-styleable name="SettingItemView">
<!-- 声明一个属性,名称:title 类型:字符串 -->
<attr name="title" format="string" />
<!-- 声明一个属性,名称:descs 类型:字符串 -->
<attr name="descs" format="string" />
</declare-styleable>
</resources>
二:在布局文件中使用自定义的属性:
1- 在根节点声明命名空间
xmlns:itcast="http://schemas.android.com/apk/res/zz.itcast.mobilesafez13"
xmlns xml name space 的缩写
itcast 是命名空间的别名
后面的是命名空间的全称,是系统默认的命名空间,最后一个android 改为我们的应用包名
2- 使用属性
<zz.itcast.mobilesafez13.view.SettingItemView
android:id="@+id/siv_auto_update"
android:layout_width="fill_parent"
itcast:title="自动更新设置"
itcast:descs="自动更新已经开启#自动更新没有开启"
android:layout_height="wrap_content"
android:background="@drawable/item_grid_bg" />
三: 在代码中获得属性,并设置给相应的控件
/**
* 在当布局文件中声明控件,由系统创建对象时,调用,我们通过findViewByID获得对象
* @param AttributeSet 布局文件中为该控件声明的属性的集合
*/
public SettingItemView(Context context, AttributeSet attrs) {
super(context, attrs);
// System.out.println("SettingItemView(Context context, AttributeSet attrs)");
int count = attrs.getAttributeCount();
for(int i=0;i<count;i++){
String name = attrs.getAttributeName(i);
String value = attrs.getAttributeValue(i);
// System.out.println(name+" : "+value);
}
String titleStr = attrs.getAttributeValue("http://schemas.android.com/apk/res/zz.itcast.mobilesafez13", "title");
String descsStr = attrs.getAttributeValue("http://schemas.android.com/apk/res/zz.itcast.mobilesafez13", "descs");
// System.out.println("titleStr::"+titleStr);
// System.out.println("descsStr::"+descsStr);
initView();
tv_title.setText(titleStr);
descs = descsStr.split("#"); // 将字符串以# 切割成字符串数组
}