自定义组合控件的过程归纳
1.写一个类继承ViewGroup,并实现三个构造方法;
2.并且在构造方法里面初始化布局文件;
3.根据需求增加API方法
---以上散步自定义组合控件----
4.为了使用组合控件更加方便,自定义组合控件
5.自定义命名空间:
xmlns:自定义名字="http://schemas.android.com/apk/res/包名"
例如:xmlns:itheima="http://schemas.android.com/apk/res/com.example.mobilesafe"
6.自定义属性,在工程res/values/attrs.xml
例如:
[代码]xml代码:
01
02
03
04
05
06
07
08
09
10
|
<!--?xml version="1.0" encoding="utf-8"?--> < font face = "黑体" > < resources > <!--属性的集合--> < declare-styleable name = "SettingItemView" > <!--定义一个String类型的属性 --> < attr name = "title" format = "string" > < attr name = "update_on" format = "string" > < attr name = "update_off" format = "string" > </ attr ></ attr ></ attr ></ declare-styleable > </ resources ></ font > |
7.使用我们自定义好的属性
例如:
[代码]xml代码:
1
|
< com.example.mobilesafe.view.settingitemview android:id = "@+id/siv_update" android:layout_width = "wrap_content" android:layout_height = "wrap_content" itheima:title = "设置自动更新" itheima:update_off = "自动更新已经关闭" itheima:update_on = "自动更新已经开启" >< font face = "黑体" > </ font ></ com.example.mobilesafe.view.settingitemview > |
8.布局文件的属性和对应的类进行管理,在自定义控件的带有两个参数的构造方法里面有一个类
AttributeSet里面封装了布局文件的属性,需要把里面的值取出来,赋值给布局文件
(1).取值:eg:update_off =attrs.getAttributeValue("http://schemas.android.com/apk/res
/com.example.mobilesafe","update_off");
(2.)赋值:eg:tv_title.setText(title);
失败是什么?没有什么,只是更走近成功一步;成功是什么?就是走过了所有通向失败的路,只剩下一条路,那就是成功的路。