android自定义属性的使用

自定义属性参数介绍(属性定义可以多种同时使用)

  • reference:参考某一资源ID。
  • color:颜色值。
  • boolean:布尔值。
  • dimension:尺寸值。
  • float:浮点值。
  • integer:整型值。
  • string:字符串。
  • fraction:百分数。
  • enum:枚举值。
  • flag:位或运算。
    以上属性在attrs文件下定义
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyTextView">
        <attr name="header" format="reference"/>
        <attr name="headerHeight" format="dimension"/>
        <attr name="headerVisibleHeight" format="dimension"/>
        <attr name="age">
            <flag name="child" value="10"/>
            <flag name="young" value="18"/>
            <flag name="old" value="60"/>
        </attr>
    </declare-styleable>
</resources>

在xml中使用这些自定义属性:

  1. 在头部添加 xmlns:attrstest=”http://schemas.android.com/apk/res-auto” (attrstest这个名称可以随意命名)
  2. 代码中获取自定义属性的值:
    通过obtainStyledAttributes方法得到TypedArray,注意最后记得回收这个TypedArray。代码如下:
TypedArray types = context.obtainStyledAttributes(attrs,
                R.styleable.MyTextView);
        int count = attrs.getAttributeCount();
        for(int i = 0;i < count;i++){
            int attr = types.getIndex(i);
            switch (attr){
                case R.styleable.MyTextView_header:

                    break;
                case R.styleable.MyTextView_headerHeight:
                    float headerHeight = types.getDimension(attr,-1);
                    break;
                case R.styleable.MyTextView_headerVisibleHeight:
                    break;
                case R.styleable.MyTextView_age:
                    break;
            }
        }
        types.recycle();

以上是最基本的介绍,更多功能后续探讨

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值