从源码看getDimension()、getDimensionPixelOffset()以及getDimensionPixelSize()三个区别

本文详细解析了Android开发中TypeArray的getDimension、getDimensionPixelOffset和getDimensionPixelSize三个方法的源码及区别。通过源码分析和简单验证,总结出这三个方法的主要差异在于返回值类型:getDimension返回float,getDimensionPixelOffset强转为int,getDimensionPixelSize则是四舍五入后的int值。
摘要由CSDN通过智能技术生成

     一、前言

我们在自定义控件的时候,通过 TypeArray(其实Resources 类也有这个方法,等等说。)的 getDimension、 getDimensionPixelSize 、getDimensionPixelOffset 可以获取到尺寸,然后,懵逼了。

     二、源码

2.1 下面会分别贴出 TypeArray 中的三个方法的源码,加了简单的中文翻译,稍微扫一眼就ok了,看看我的翻译就先过去

2.2  getDimension  的源码,保留了源码中的原始说明,毕竟我翻译的很low,自己看不下去但是又翻译不好。

    /**
     * Retrieve a dimensional unit attribute at <var>index</var>. Unit
     * conversions are based on the current {@link DisplayMetrics}
     * associated with the resources this {@link TypedArray} object
     * came from.
     *
     * 通过指定的 参数inde 获得一个尺寸的单位属性。该单位转换是基于你当前机器屏幕的DisplayMetrics
     * 以及和当前TypedArray 的对象持有的资源而得到的,
     * <p>
     * This method will throw an exception if the attribute is defined but is
     * not a dimension.
     * 当属性不是尺寸的时候,即使确实被定义了,也会抛出一个异常的。
     * @param index Index of attribute to retrieve.
     * @param defValue Value to return if the attribute is not defined or
     *                 not a resource.
     *
     * @return Attribute dimension value multiplied by the appropriate
     *         metric, or defValue if not defined.
     *         结果将被乘上一个合适的 metric
     * @throws RuntimeException if the TypedArray has already been recycled.
     *          如果当前TypedArray 被recycle 会抛异常
     * @throws UnsupportedOperationException if the attribute is defined but is
     *         not an integer.
     *         如果定义的属性不是整形,会抛异常
     *
     * @see #getDimensionPixelOffset
     * @see #getDimensionPixelSize
     */
    public float getDimension(int index, float defValue) {
        if (mRecycled) {
            throw new RuntimeException("Cannot make calls to a recycled instance!");
        }

        index *= AssetManager.STYLE_NUM_ENTRIES;
        final int[] data = mData;
        final int type = data[index+AssetManager.STYLE_TYPE];
        if (type == TypedValue.TYPE_NULL) {
            return defValue;
        } else if (type == TypedValue.TYPE_DIMENSION) {
            /**
             * 这里就是我们获取结果走的方法
             */
            return TypedValue.complexToDimension(
                    data[index + A
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值