1

related SO question

We can define custom attribute of multiple types.

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

And I want to use it in the following way

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

How to read the value out of it?


API level 21 provided an 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);
}

I guess this is the recommended solution.

But how to do it with lower API level? Do I have to use try catch?

Or maybe just define two attributes... cornerRadius and cornerRadiusPercentage... I'm going to miss border-radius in CSS.

Community
  • 1
  • 1
lzl124631x
  • 4,485
  • 2
  • 30
  • 49

1 Answers1

2

Thanks for @Selvin's comment. You can use TypedArray.getValue(...) + TypedValue.type. You can find the type constants 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;
}
lzl124631x
  • 4,485
  • 2
  • 30
  • 49
  • why not `mCornerRadius = tv.getFraction(1,1);` and `mCornerRadius = tv.getDimension(getContext().getResources().getDisplayMetrics());` ? – Selvin Feb 09 '17 at 13:21