美文网首页程序员Android开发
TypedArray 和 Resources 的 getFrac

TypedArray 和 Resources 的 getFrac

作者: JamFF | 来源:发表于2019-04-29 14:35 被阅读6次

在自定义属性中如果我们想使用百分比,那就需要设置 format="fraction",例如下面:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyPercentLayout_Layout">
        <attr name="widthPercent" format="fraction" />
        <attr name="heightPercent" format="fraction" />
        <attr name="marginLeftPercent" format="fraction" />
        <attr name="marginRightPercent" format="fraction" />
        <attr name="marginTopPercent" format="fraction" />
        <attr name="marginBottomPercent" format="fraction" />
    </declare-styleable>
</resources>

解析属性:

public LayoutParams(Context c, AttributeSet attrs) {
    super(c, attrs);
    // 这里注意,LayoutParams的styleable有命名规范,要以外部类的类名加_Layout结尾,这样才能在xml布局中有提示
    TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.MyPercentLayout_Layout);
    // 解析自定义属性
    widthPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_widthPercent, 1, 1, 0);
    heightPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_heightPercent, 1, 1, 0);
    marginLeftPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_marginLeftPercent, 1, 1, 0);
    marginRightPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_marginRightPercent, 1, 1, 0);
    marginTopPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_marginTopPercent, 1, 1, 0);
    marginBottomPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_marginBottomPercent, 1, 1, 0);
    a.recycle();
}

我们的主角 getFraction()登场,第一个参数和最后一个参数很好理解,重点是 base 和 pbase 两个参数,一般使用时两个参数都传 1,但具体代表什么含义,网上资料非常少,有的人说 base 代表分子乘的系数,pbase 代表分母乘的系数,这完全是错误的。

先看下官方给出的注释吧。

官方注释

还是不好理解,我们分析下源码。

/**
 * Retrieves a fractional unit attribute at <var>index</var>.
 *
 * @param index Index of attribute to retrieve.
 * @param base The base value of this fraction.  In other words, a
 *             standard fraction is multiplied by this value.
 * @param pbase The parent base value of this fraction.  In other
 *             words, a parent fraction (nn%p) is multiplied by this
 *             value.
 * @param defValue Value to return if the attribute is not defined or
 *                 not a resource.
 *
 * @return Attribute fractional value multiplied by the appropriate
 *         base value, or defValue if not defined.
 * @throws RuntimeException if the TypedArray has already been recycled.
 * @throws UnsupportedOperationException if the attribute is defined but is
 *         not a fraction.
 */
public float getFraction(@StyleableRes int index, int base, int pbase, float defValue) {
    if (mRecycled) {
        throw new RuntimeException("Cannot make calls to a recycled instance!");
    }

    final int attrIndex = index;
    index *= STYLE_NUM_ENTRIES;

    final int[] data = mData;
    final int type = data[index + STYLE_TYPE];
    if (type == TypedValue.TYPE_NULL) {
        return defValue;
    } else if (type == TypedValue.TYPE_FRACTION) {
        return TypedValue.complexToFraction(data[index + STYLE_DATA], base, pbase);// 关键代码
    } else if (type == TypedValue.TYPE_ATTRIBUTE) {
        final TypedValue value = mValue;
        getValueAt(index, value);
        throw new UnsupportedOperationException(
                "Failed to resolve attribute at index " + attrIndex + ": " + value);
    }

    throw new UnsupportedOperationException("Can't convert value at index " + attrIndex
            + " to fraction: type=0x" + Integer.toHexString(type));
}

看到 base 和 pbase 只在一处有使用,跟进去:

public static float complexToFraction(int data, float base, float pbase) {
    switch ((data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK) {
        case COMPLEX_UNIT_FRACTION:
            return complexToFloat(data) * base;
        case COMPLEX_UNIT_FRACTION_PARENT:
            return complexToFloat(data) * pbase;
    }
    return 0;
}

这里面只做了一件事,根据 data 进行判断,将取到的属性值分别乘以 base 或者 pbase 最后返回。

到这里大致可判断出:

  • base,返回的百分比为属性值乘以 base。
  • pbase,返回的百分比为属性值乘以 pbase。
  • base 和 pbase 同时设置只会有一个生效,因为上面 return 中只能使用一个参数。

一、base参数

布局中设置 heightPercent 和 widthPercent 均为百分比为 25%:

<?xml version="1.0" encoding="utf-8"?>
<com.ff.screenadapter.percent.MyPercentLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:text="宽25%;高25%"
        android:textColor="@android:color/white"
        app:heightPercent="25%"
        app:widthPercent="25%"
        tools:ignore="MissingPrefix" />

</com.ff.screenadapter.percent.MyPercentLayout>

设置 base 为 1:

widthPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_widthPercent, 1, 1, 0);
heightPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_heightPercent, 1, 1, 0);

效果为屏幕宽高的 25%:


宽高为25%

设置 base 为 2:

widthPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_widthPercent, 2, 1, 0);
heightPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_heightPercent, 2, 1, 0);

效果为屏幕宽高的 50%:


宽高为50%

效果很明显,在不改变布局的情况下,修改 base 的值,得到的结果确实是,百分比属性乘以 base 之后的值。

二、pbase参数

还是使用上面布局,只是将 pbase 设置为 2:

widthPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_widthPercent, 1, 2, 0);
heightPercent = a.getFraction(R.styleable.MyPercentLayout_Layout_heightPercent, 1, 2, 0);

效果依然为屏幕宽高的 25%,并没有生效。

这里就需要引用一个新的百分比参数 25%p,没错,后面的 p 不是手误敲上。

  • 25% 表示相对于对象自身的百分比。
  • 25%p 表示相对于父容器的百分比,percent of parent。

我们再来修改下 layout,使用 25%p

<?xml version="1.0" encoding="utf-8"?>
<com.ff.screenadapter.percent.MyPercentLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:text="宽25%;高25%"
        android:textColor="@android:color/white"
        app:heightPercent="25%p"
        app:widthPercent="25%p"
        tools:ignore="MissingPrefix" />

</com.ff.screenadapter.percent.MyPercentLayout>

现在可以看到效果来,宽高为屏幕宽高的 50%:


宽高为50%

三、总结

  • base 表示百分比资源的基值,返回结果为 nn% * base 的结果值。
  • pbase 表示 %p 形态百分比资源的基值,返回结果为 nn%p * pbase 的结果值。
  • 同时设置 base 和 pbase 只会有一个生效,取决与百分比是否以 p 结尾。
  • 不论是 TypedArray 的 getFraction() 还是 Resources 的 getFraction(),都是上述结论。

如果看到这里,还不能理解的话,可以看 stackoverflow 上面的一个例子,可能更好理解:

<item name="fraction" type="fraction">5%</item>
<item name="parent_fraction" type="fraction">2%p</item>
// 0.05f
getResources().getFraction(R.fraction.fraction, 1, 1);
// 0.02f
getResources().getFraction(R.fraction.parent_fraction, 1, 1);
// 0.10f
getResources().getFraction(R.fraction.fraction, 2, 1);
// 0.10f
getResources().getFraction(R.fraction.fraction, 2, 2);
// 0.04f
getResources().getFraction(R.fraction.parent_fraction, 1, 2);
// 0.04f
getResources().getFraction(R.fraction.parent_fraction, 2, 2);

相关文章

网友评论

    本文标题:TypedArray 和 Resources 的 getFrac

    本文链接:https://www.haomeiwen.com/subject/kanenqtx.html