【发布时间】:2017-06-27 11:14:12
【问题描述】:
我们可以定义多种类型的自定义属性。
<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吗?
或者也许只是定义两个属性...cornerRadius 和 cornerRadiusPercentage...我会想念 CSS 中的border-radius。
【问题讨论】:
-
TypedArray.getValue(...)+TypedValue.type? -
@Selvin 我正在尝试您的解决方案。我认为它会起作用。谢谢。
-
@Selvin 您可以发布答案。我会接受的。