Android 自定义控件属性

来源:互联网 发布:乐高编程机器人难不难 编辑:程序博客网 时间:2024/06/03 22:39

Android declare-styleable自定义控件属性

  • 第一步: 在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>  
  • 第二步:使用,自定义属性的使用是在布局中使用
  • Android 4.0 以后可以使用 xmlns:app=”http://schemas.android.com/apk/res-auto”

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

    • 注意要在有三个参数的构造方法中才能获取到。
  • 关于自定义属性的设置问题:

    • fomat的属性自己定义 根据自己的需要来选择string , integer , dimension , reference , color , enum……
    • reference:参考指定Theme中资源ID。
    • dimension:尺寸值
    • float:浮点型
    • boolean:布尔值
    • integer:整型
    • string:字符串
    • fraction:百分数
    • flag:位或运算
    • Color:颜色
    • enum:枚举
    • *
  • 其他都很简单,一看就会,枚举的特殊些,就是把能选的值列举出来,在布局中设置属性的时候就只能选择在attr.xml中定义的枚举的值

    <attr name="direction" format="enum">      <enum name="rightToLeft" value="0" />      <enum name="bottomToTop" value="1" />      <enum name="leftToRight" value="2" />      <enum name="topToBottom" value="3" />  </attr>  
  • 在使用的时候如图:在构造方法中取值就会取到对应的value中的值。

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

    <declare-styleable name = "名称">        <attr name="background" format="reference|color" /></declare-styleable>
  • 使用:

    <ImageView android:background = "@drawable/图片ID|#00FF00"/>
0 0
原创粉丝点击