Add floating point value to android resources/values Ask Question

Add floating point value to android resources/values Ask Question

I'm trying to add a little space between lines to my TextViews using android:lineSpacingMultiplier from the documentation:

Extra spacing between lines of text, as a multiplier.

Must be a floating point value, such as "1.2".

As I'm using this in a few different TextViews I would like to add a global dimension/value to my resources, but I don't know which tag to use, if it even exists. I have tried all resource types that make sense to me, but none of them works.

What I would like to have would be something like this:

<resources>
    <dimen name="text_line_spacing">1.4</dimen>
</resources>

Edit: I'm aware of android:lineSpacingExtra (which needs a dimension with an appended unit), but I'd like to use android:lineSpacingMultiplier if possible.

ベストアンサー1

There is a solution:

<resources>
    <item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>

In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:

Format = enclosing data type:

  • float
  • boolean
  • fraction
  • integer
  • ...

and type stands for:

Type = resource type (referenced with R.XXXXX.name):

  • color
  • dimen
  • string
  • style
  • etc...

To fetch resource from code, you should use this snippet:

TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();  

I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)), but Android dimensions have special treatment and pure "float" number is not valid dimension.


Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.

<resources>
    <dimen name="text_line_spacing">2.025px</dimen>
</resources>

and from code, you can get that float by

float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);

in this case, value of lineSpacing is 2.024993896484375, and not 2.025 as you would expected.

おすすめ記事