Android给自定义控件添加自定义属性

来源:互联网 发布:淘宝网店发货流程 编辑:程序博客网 时间:2024/05/18 22:10

很多时候我们会写一些自定义组建或者是重写一些组建,但是我们常常会想系统组建为什么会有各自不同的属性,我们能否为自己的组建定义一些属性,看了我们头儿写的代码,我发现,写自定义属性其实非常简单,只是以前我不知道,呵呵,好了,下面就说说如何实现自定义属性:

属性文件的定义是定义在一个xml文件中的:

里面的结构如下:

<resources>

     <declare-styleable  name="DZHLayout">

             <attr name="type" format="integer"/>

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

             <attr name="scroll" format="boolean"/>

             <attr name="backdrawable" format="reference"/>

             <attr name="headdrawable" format="reference"/>

             <attr name="rightid" format="integer"/>

            <attr name="leftid" format="integer"/>

     </declare-styleable>

</resources>

 这里声明了一个布局中的一组属性,有type,title等等。具体怎么用呢。

在我们的布局文件中使用自定义控件时:

有人说,定义也定义好了,也引用了,在我们的自定义组建中如何获取到这些属性值呢,下面以一个CustomTitle自定义组建为例:

public CustomTitle(Context context, AttributeSet attrs) {

        super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs, styleable.DZHLayout);

        type = a.getInt(styleable.DZHLayout_type, 0);

        title = a.getString(styleable.DZHLayout_title);

        a.recycle();

}

在构造函数中通过这种方式获取到我们的属性值。