2017-02-09 47 views
0

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

+0

'TypedArray.getValue(...)'+'TypedValue.type'? – Selvin

+0

@Selvin我正在尝试你的解决方案。我认为它会起作用。谢谢。 – Moon

+0

@Selvin你可以发表一个答案。我会接受它。 – Moon

回答

0

感谢@ Selvin的评论。您可以使用TypedArray.getValue(...)​​。你可以找到类型常量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; 
} 
+0

为什么不''mCornerRadius = tv.getFraction(1,1);''和'mCornerRadius = tv.getDimension(getContext()。getResources()。getDisplayMetrics());'? – Selvin

+0

@Selvin谢谢!我正在赶工工作...更新。 – Moon