09自定义组合控件总结

来源:互联网 发布:网络诈骗案立案 编辑:程序博客网 时间:2024/05/17 20:43

第一步:

自定义一个View,一般来说,继承了相对布局或者线性布局。(必须为ViewGroup的子类)

第二步:

实现父类的构造方法,一般来说,需要在构造方法里初始化自定义的布局文件

第三步:

根据一些需要,定义一些API方法。

//============================================

第四步:

根据需要,自定义控件的属性,可以参照TextView的属性;

第五步:

自定义命名空间,例如:

 xmlns:owndefine="http://schemas.android.com/apk/res/com.ustc.mobilemanager"

后面的是应用的包名。

第六步:

自定义属性,在res/values目录下的attrs.xml文件

如:

<?xml version="1.0" encoding="utf-8"?><resources>         <declare-styleable name="TextView">        <attr name="title" format="string" />        <attr name="desc_on" format="string" />        <attr name="desc_off" format="string" />    </declare-styleable>     </resources>


第七步:

使用我们自定义的属性。

如:

<attr name="title" format="string" />        <attr name="desc_on" format="string" />        <attr name="desc_off" format="string" />


第八步:

在自定义控件的带有两个参数的构造方法里,使用AttributeSet取出属性值,取出后关联自定义布局文件对应的控件。

String title = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.ustc.mobilemanager","title");desc_on = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.ustc.mobilemanager","desc_on");desc_off = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.ustc.mobilemanager","desc_off");tv_title.setText(title);




0 0