Android自定义控件属性

接上一篇

当我们定义了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自定义控件属性以及用法完成。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值