slup slup - 1 year ago 120
Android Question

Add floating point value to android resources/values

I'm trying to add a little space between lines to my TextViews using


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:

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

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

Answer Source

There is a solution:

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

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

  • 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.

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download