【问题标题】:How to read value of custom attribute of multiple formats?如何读取多种格式的自定义属性值?
【发布时间】:2017-06-27 11:14:12
【问题描述】:

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

【问题讨论】:

  • TypedArray.getValue(...) + TypedValue.type ?
  • @Selvin 我正在尝试您的解决方案。我认为它会起作用。谢谢。
  • @Selvin 您可以发布答案。我会接受的。

标签: android android-studio


【解决方案1】:

感谢@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;
}

【讨论】:

  • 为什么不mCornerRadius = tv.getFraction(1,1);mCornerRadius = tv.getDimension(getContext().getResources().getDisplayMetrics());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 2013-04-16
  • 2011-03-10
  • 1970-01-01
相关资源
最近更新 更多