加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

declare-styleable自定义控件属性

发布时间:2020-12-16 09:18:20 所属栏目:百科 来源:网络整理
导读:今天研究了一下android控件的自定义属性的使用:方便以后的使用,防止忘记就记录一下。 第一步: 在values文件夹下面建立attr.xml文件,在这个文件中定义自定义属性 比如: ?xml version="1.0" encoding="utf-8"?resources declare-styleable name="MultiDir

今天研究了一下android控件的自定义属性的使用:方便以后的使用,防止忘记就记录一下。


第一步: 在values文件夹下面建立attr.xml文件,在这个文件中定义自定义属性


比如:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MultiDirectionSlidingDrawer">
	    <attr name="handle" format="dimension"></attr>
	    <attr name="content" format="dimension"></attr>
	    <attr name="allowSingleTap" format="boolean"></attr>
	    <attr name="animateOnClick" format="boolean"></attr>
	    <attr name="bottomOffset" format="dimension"></attr>
	    <attr name="topOffset" format="dimension"></attr>
            <attr name="direction" >
                <enum name="rightToLeft" value="0" />
	            <enum name="bottomToTop" value="1" />
	            <enum name="leftToRight" value="2" />
	            <enum name="topToBottom" value="3" />
            </attr>
    </declare-styleable>
</resources>


第二步:使用,自定义属性的使用是在布局中使用





第三步:在自定义控件中使用。

注意要在有三个参数的构造方法中才能获取到。


第一部分的命名就是declare-styleable 后面name对应的值

使用后记得调用一下gc释放资源

 a.recycle();  


关于自定义属性的设置问题:

fomat的属性自己定义 根据自己的需要来选择string,integer,dimension,reference,color,enum......

reference:参考指定Theme中资源ID。

dimension:尺寸值

float:浮点型

boolean:布尔值

integer:整型

string:字符串

fraction:百分数

flag:位或运算

Color:颜色

enum:枚举

其他都很简单,一看就会,枚举的特殊些,就是把能选的值列举出来,在布局中设置属性的时候就只能选择在attr.xml中定义的枚举的值

比如:

<attr name="direction" >
            <enum name="rightToLeft" value="0" />
	        <enum name="bottomToTop" value="1" />
	        <enum name="leftToRight" value="2" />
	        <enum name="topToBottom" value="3" />
        </attr>

在使用的时候如图: 在构造方法中取值就会取到对应的value中的值。


属性定义时可以指定多种类型值:

1
2
3
    <declare-styleable name = "名称"> <attr name="background"       format="reference|color" /> </declare-styleable>

使用:

1
<ImageView android:background = "@drawable/图片ID|#00FF00"/>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
    站长推荐
    热点阅读