问题
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();
回答1:
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"
回答2:
You dont need a TypedValue
use the following
(int) this.getResources().getDimension(R.integer.quantity_length)
;
回答3:
int max = getContext().getResources().getInteger(R.integer.quantity_length);
回答4:
With your example, why don't you use this method?
XML
<integer name="quantity_length">10</integer>
JAVA
getResources().getInteger(R.integer.quantity_length);
回答5:
Use:
Integer.ParseInt(digitsBefore);
回答6:
I tested with Android Studio 3.3.1 with SDK lollipop
Keep an eye on the paths...
Clean and build... I had a pretty hard time, thinking it's not working, but after deleting the file and Re-add, and few clean and build, I got it working strange...
1. This works ( note the tick and its path)
2. Here is proof
来源:https://stackoverflow.com/questions/27782074/get-integer-value-from-dimens-xml-resource-file-in-android