自定义控件自定义属性步骤

自定义属性步骤:
参数系统属性声明: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("#"); // 将字符串以# 切割成字符串数组

} 




 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值