Android 自定义控件大道(一) 自定义属性

一、自定义属性

首先在values的资源文件夹下创建一个attrs的文件。
属性写上

  <declare-styleable name="CustomView">
        <attr name="color" format="color"/>
  </declare-styleable>

其中declare-styleable下的name是你的自定义控件的名字,attr标签下的name是你要添加的属性的名字,format是它的格式。
共有10种:

1.reference:引用某一资源ID。

使用:

    app:reference = "@color/颜色ID"
    或者
    app:reference = "#aabbcc"
2.color:颜色值

使用:

     app:color="#aabbcc"
3.boolean:布尔值。(不做解释)
4.dimension:尺寸值。

例如dp和sp等值要使用这个格式

     app:dimension="30dp"
5.float:浮点值。
     app:float="0.7"
6.integer:整型值。(不做解释)
7.string: 字符串。(不做解释)
8.fraction:百分数。
     app:fraction="300%"
9.enum:枚举值。

定义:

  <declare-styleable name="CustomView">
      <attr name="enum">
          <enum name="example_one" value="0" />
          <enum name="example_two" value="1" />
      </attr>            
</declare-styleable>

使用:

    app:enum = "exampleone"
10.flag:位或运算。

定义:

<attr name="flags">
    <flag name = "example_one" value = "1"/>
    <flag name = "example_two" value = "2"/>
    <flag name = "example_three" value = "3"/>
    <flag name = "example_four" value = "4"/>
</attr>

使用:

app:flags="example_four|example_one|example_two|example_three"

另外需要注意的是: 属性定义时可以指定多种类型值。中间使用 | 分隔即可。

二、获取自定义的属性

public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
    int customColor = ta.getColor(R.styleable.CustomView_color, Color.BLUE);
    ta.recycle();
    }

获取属性就是通过TypedArray对象来get,什么类型的属性就用对应的get方法。

注意使用完TypedArray对象后需要释放它。ta.recycle()。
原因是它是一个池+单例模式,程序在运行时维护了一个 TypedArray的池,程序调用时,会向该池中请求一个实例,用完之后,调用 recycle() 方法来释放该实例,从而使其可被其他模块复用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值