gpt4 book ai didi

android - 如何读取多种格式的自定义属性值?

转载 作者:行者123 更新时间:2023-11-29 19:22:28 24 4
gpt4 key购买 nike

related SO question

我们可以定义多种类型的自定义属性。

<declare-styleable name="RoundedImageView">
<attr name="cornerRadius" format="dimension|fraction"/>
</declare-styleable>

我想按以下方式使用它

<RoundedImageView app:cornerRadius="30dp"/>
<RoundedImageView app:cornerRadius="20%"/>

如何读取其中的值?


API 级别 21 提供了一个 API TypedArray.getType(index)

int type = a.getType(R.styleable.RoundedImageView_cornerRadius);
if (type == TYPE_DIMENSION) {
mCornerRadius = a.getDimension(R.styleable.RoundedImageView_cornerRadius, 0);
} else if (type == TYPE_FRACTION) {
mCornerRadius = a.getFraction(R.styleable.RoundedImageView_cornerRadius, 1, 1, 0);
}

我想这是推荐的解决方案。

但是如何使用较低的 API 级别来实现呢?我必须使用 try catch 吗?

或者也许只定义两个属性...cornerRadiuscornerRadiusPercentage...我会错过 CSS 中的 border-radius .

最佳答案

感谢@Selvin 的评论。您可以使用 TypedArray.getValue(...) + TypedValue.type。您可以找到类型常量 here

TypedValue tv = new TypedValue();
a.getValue(R.styleable.RoundedImageView_cornerRadius, tv);
if (tv.type == TYPE_DIMENSION) {
mCornerRadius = tv.getDimension(getContext().getResources().getDisplayMetrics());
} else if (tv.type == TYPE_FRACTION) {
mCornerRadius = tv.getFraction(1, 1);
mUsePercentage = true;
}

关于android - 如何读取多种格式的自定义属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42136793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com