31

As I understood from available Android Resource types, there is no straight way to use float values as resources, unless you use some hacks such as the one mentioned in here. Is there any convention or something for this?

Community
  • 1
  • 1
Pooya
  • 531
  • 1
  • 5
  • 10
  • try to define float or double as string and convert it to appropriate at run time. – Haresh Chhelana May 01 '15 at 10:13
  • Android could provide Integer or Boolean type values the way that you mentioned, but why there are specific type values such as Integer or Boolean but not Float? what is the reason? – Pooya May 01 '15 at 10:33
  • Check out : http://stackoverflow.com/questions/29967258/typedarray-is-empty-after-obtaintypedarray-call/29968037#29968037 – Haresh Chhelana May 01 '15 at 10:37

3 Answers3

39

No, There is no direct resource type is provided for float/double.

But Yes there is two hacks to do that.

1) In dimens.xml

<item name="float" type="dimen" format="float">9.52</item>

Referencing from java

TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();

And Second is as Bojan and Haresh suggested, To use value as string and parse it in your code at runTime.

Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
Kirankumar Zinzuvadia
  • 1,249
  • 10
  • 17
20

Add a float to dimens.xml:

<item format="float" name="my_dimen" type="dimen">0.54</item>

To reference from XML:

<ImageView 
    android:alpha="@dimen/my_dimen"
    ...

To read this value programmatically you can use ResourcesCompat.getFloat from androidx.core

Gradle dependency:

implementation("androidx.core:core:${version}")

Usage:

import androidx.core.content.res.ResourcesCompat;

...

float value = ResourcesCompat.getFloat(context.getResources(), R.dimen.my_dimen);
Alex Baker
  • 1,537
  • 2
  • 13
  • 28
17

Just save your double as a String resource

<string name="some_decimal">0.12154646</string>

And then just parse that in your code like this

double some_decimal = Double.parseDouble(context.getString(R.string.some_decimal));

You can also make your own type of resource values and get it from there like this

<item name="some_decimal" type="vals" format="float">2.0</item>

And then get it like this

TypedValue tempVal = new TypedValue();
getResources().getValue(R.vals.some_decimal, tempVal, true);
float some_decimal = tempVal.getFloat();

But it's impossible to get doubles like this and also I think that it's less performant than just simply parsing a string resource, so I prefer my first option.

Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
  • Be aware! Don't retrieve such strings by "getResources().getString(R.string.YourStringTag)", this will return "Experimental" as string. – Dexter Apr 16 '16 at 05:42