自定义控件5---TypedArray和AttributeSet

API—TypedArray | Android 开发者
API—AttributeSet | Android 开发者

1 TypedArray的两种初始化方式:

//      TypedArray typedArray=context.getTheme().obtainStyledAttributes(R.styleable.mtextview);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.mtextview);

2 TypedArray和AttributeSet的区别

我们用自定义控件1—TextView 中的demo做测试
首先在OneTextView的构造方法中添加测试代码

        int attrCount = attrs.getAttributeCount();
        //打印AttribuseSet的数量
        Log.e("pepe", "AttribuseSet---attrCount="+attrCount);
        for (int i = 0; i < attrCount; i++) {
            String attrName = attrs.getAttributeName(i);
            String attrVal = attrs.getAttributeValue(i);
            //打印属性名和对应的属性值
            Log.e("pepe", "AttribuseSet---attrName = " + attrName + " , attrVal = " + attrVal);
        }

        int typedCount=typedArray.getIndexCount();
        //打印TypedArray的数量
        Log.e("pepe", "TypedArray---typedCount="+typedCount);
        //打印自定义的三个属性值
        Log.e("pepe", "TypedArray---text = " + mText);
        Log.e("pepe", "TypedArray---mTextColor = " + mTextColor);
        Log.e("pepe", "TypedArray---mTextSize = " + mTextSize);

接着我对布局中的自定义控件做了修改

    <com.pepe.widgetdemo.OneTextView 
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:text="第一个"
        custom:textColor="#00ff00"
        custom:textSize="20sp"
        />
    <com.pepe.widgetdemo.OneTextView 
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="10dp"
        custom:text="@string/twoText"
        custom:textColor="@color/twoColor"
        custom:textSize="@dimen/twoSize"
        />

对应的string、color、dimen为

    <string name="twoText">第二个</string>
    <color name="twoColor">#0000ff</color>
    <dimen name="twoSize">20sp</dimen>

打印结果如下:
第一个OneTextView
这里写图片描述

第二个OneTextView
这里写图片描述

通过对比,可以发现,通过AttributeSet取到的值是原生的
如果xml文件中的值是引用的value,要使用AttributeSet去获得最终的值,需要第一步拿到id,第二步再去解析id。而TypedArray正是帮我们简化了这个过程,取到的则是经过转换的值。

其他:

可能有人会有疑问,打印出来的mTextSize为什么会是60。
这个60的单位是px,是根据测试手机的分辨率转换过来的。
下面提供两个px和sp互相转换的方法:

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
     final float scale = context.getResources().getDisplayMetrics().density;
     return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
     final float scale = context.getResources().getDisplayMetrics().density;
     return (int) (pxValue / scale + 0.5f);
    }

源码下载

引用:
Android 深入理解Android中的自定义属性 - Hongyang - 博客频道 - CSDN.NET
Android开发学习之TypedArray类 - richerg85的专栏 - 博客频道 - CSDN.NET

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值