Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android float/double resource type

Tags:

android

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?

like image 812
Pooya Avatar asked Sep 03 '25 15:09

Pooya


2 Answers

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.

like image 90
Kirankumar Zinzuvadia Avatar answered Sep 05 '25 06:09

Kirankumar Zinzuvadia


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);
like image 32
Alex Baker Avatar answered Sep 05 '25 06:09

Alex Baker