Android 自定义 attr属性

最近在封装一些 自定义的View 遇到了一些 自定义attr 属性的问题, 这里来复习总结下:

1. 定义attire 属性

在res/values  文件下新建一个attrs.xml 里面都是些 attr 属性相关的文件

在里面可以自己 定义 属性 如下: 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="textColor" format="color"/>
        <attr name="textSize" format="dimension"/>
    </declare-styleable>
    <declare-styleable name="MyImageView">
        <attr name="imgSrc" format="reference"/>
    </declare-styleable>
</resources>

上面的内容很容易理解,  需要注意的是 format 有以下几种类型:
1.reference:参考某一资源ID( 图片资源之类的)
2. color:颜色值
3. boolean:布尔值
4. dimension:尺寸值
5. float:浮点值
6. integer:整型值
7. string:字符串
8. fraction:百分数
9. enum:枚举值
10. flag:位或运算 

具体的用法 更详细的内容 可以参考这片文章, 这些  format都介绍的很详细


2. 使用自定义的 attr属性
为了让布局文件能够认识我们定义的属性, 不至于我们在写这些自定义的属性报错是, 需要加入如下schemas:
http://schemas.android.com/apk/res/[your package name]
例子如下: 
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.zuimeia.imagewidthnumview.ImageWithNumView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:textColor="@color/blue"
        app:textSize="13sp"/>
</RelativeLayout>

旧的官方文档建议使用使用第一种,  
但现在建议使用第二种  (Android Studio 强烈建议使用第二种)自动去寻找哪些属性,  就是 代码提示好像有点问题 

3. 读取attr
我们在xml 定义了 属性, 需要在View 中读取出这些属性 例子如下: 
public ImageWithNumView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
    int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
    float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
    LogUtil.d(TAG, "textColor = " + textColor);
    LogUtil.d(TAG, "textSize = " + textSize);

}

通过上面的方式 就可以读取我定义的attr属性了
AttributeSet 相关文档, 里面还有一些其他相关的方法


通过AttributeSet 获取定义的宽高: 
for (int i = 0; i < attrs.getAttributeCount(); i++) {
    if ("layout_height".equals(attrs.getAttributeName(i))) {
        String h = attrs.getAttributeValue(i);
        LogUtil.d(TAG, "h = " + h);
    } else if ("layout_width".equals(attrs.getAttributeName(i))) {
        String w = attrs.getAttributeValue(i);
        LogUtil.d(TAG, "w = " + w);
    }
}
打出来的log 是这样的:
ImageWithNumView: w = 10.0dip
ImageWithNumView: h = 20.0dip














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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值