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
吗?
或者,也许只是定义两个属性... cornerRadius
和cornerRadiusPercentage
...我想在CSS中错过border-radius
。
'TypedArray.getValue(...)'+'TypedValue.type'? – Selvin
@Selvin我正在尝试你的解决方案。我认为它会起作用。谢谢。 – Moon
@Selvin你可以发表一个答案。我会接受它。 – Moon