Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get integer value from dimens.xml resource file in Android

I have an EditText which is decimal and I set its length using android:maxLength property in xml:

    <EditText
        android:id="@+id/quantity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal"
        android:singleLine="true"
        android:maxLength="@integer/quantity_length" />

As its length is going to be used not only in the UI xml file but also in a java class and maybe some other places, I want to avoid problems when I update this value in future, so I want to put the length centralized in the dimens.xml resource file as follows:

dimens.xml

<resources>

    <!-- other things -->

    <!-- Constants -->
    <item name="quantity_length" format="integer" type="integer">10</item>

    <!-- other things -->

</resources>

From a java class I need to read this value so I perform:

    TypedValue typedValue = new TypedValue();
    this.getResources().getValue(R.integer.quantity_length, typedValue, true);

but I can notice that there is no method getInt(), only getFloat():

    int digitsBefore = typedValue.getFloat();

so as I need to get it as integer.... how to do this? Of course, maybe I can get it using getFloat() and then casting to integer.... but I do not know if it is an elegant way to do it... so any ideas?

UPDATE: Oooppssss I did a mistake. It is: int quantity = typedValue.getFloat();

instead of:

int digitsBefore = typedValue.getFloat();
like image 266
Ralph Avatar asked Jan 05 '15 14:01

Ralph


3 Answers

Why not store the integer in res/integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="quantity_length">12</integer>
</resources>

And to access the values in code

int myInteger = getResources().getInteger(R.integer.quantity_length);

Or in XML

android:maxLength="@integer/quantity_length"
like image 114
Marko Avatar answered Nov 19 '22 19:11

Marko


With your example, why don't you use this method?

XML

<integer name="quantity_length">10</integer>

JAVA

getResources().getInteger(R.integer.quantity_length);
like image 36
Anthone Avatar answered Nov 19 '22 18:11

Anthone


You dont need a TypedValue use the following

(int) this.getResources().getDimension(R.integer.quantity_length);

like image 1
ashkhn Avatar answered Nov 19 '22 19:11

ashkhn