接上一篇
当我们定义了android自定义控件之后,目的是重复利用,当我们重复利用它的的时候:
if (update) {
//上一次已选中
sItemView.setChecked(update);
sItemView.setDec("自动更新已经打开");
} else {
//上一次未选中
sItemView.setChecked(update);
sItemView.setDec("自动更新已经关闭");
}
可以发现,xml 中的settingItemView可以复制,但是其中的textView内容是需要每次都设置的,那么问题来了,如何才能避免每次去判断当前是否选中之后去设置textView内容呢?
那就是去定义自定义控件的属性,当我们每次复制之后,只需要修改属性值就OK。
步骤:
1.设置命名空间:
xmlns:honeybee="http://schemas.android.com/apk/res/com.honeybee.mobilesafe"
2.添加honeybee的属性
在value目录下新建attrs.xml(应该是不可以改名字的,编译系统会自动寻找,尚未考证)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="honeybee">
<attr name="set_title" format="string" />
<attr name="desc_on" format="string" />
<attr name="desc_off" format="string" />
</declare-styleable>
</resources>
3.添加自定义属性:
<com.honeybee.mobilesafe.ui.SettingItemView
android:id="@+id/setting_item"
honeybee:set_title="设置是否自动更新"
honeybee:desc_on="自动更新已经打开"
honeybee:desc_off="自动更新已经关闭"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
大部分工作算是完成了,但此时并未在view初始化时候将属性值显示出来。
4.在SettingItemView构造方法中实例化以上属性,并在setChecked()方法中显示desc_on or off
public SettingItemView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
title = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.honeybee.mobilesafe","set_title");
descOn = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.honeybee.mobilesafe","desc_on");
descOff = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.honeybee.mobilesafe","desc_off");
textView1.setText(title);
}
public void setChecked(boolean checked) {
checkBox.setChecked(checked);
if (checked) {
textView2.setText(descOn);
} else {
textView2.setText(descOff);
}
}
至此,android自定义控件属性以及用法完成。