从Android中的dimens.xml资源文件中获取整数值

use*_*552 11 android android-resources

我有一个十进制的EditText,我使用xml中的android:maxLength属性设置它的长度:

    <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" />
Run Code Online (Sandbox Code Playgroud)

因为它的长度不仅会在UI xml文件中使用,而且还会在java类和其他一些地方使用,我希望在将来更新此值时避免出现问题,因此我希望将长度集中在dimens.xml资源文件如下:

dimens.xml

<resources>

    <!-- other things -->

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

    <!-- other things -->

</resources>
Run Code Online (Sandbox Code Playgroud)

从java类我需要读取这个值,所以我执行:

    TypedValue typedValue = new TypedValue();
    this.getResources().getValue(R.integer.quantity_length, typedValue, true);
Run Code Online (Sandbox Code Playgroud)

但我可以注意到没有方法getInt(),只有getFloat():

    int digitsBefore = typedValue.getFloat();
Run Code Online (Sandbox Code Playgroud)

所以我需要把它作为整数....如何做到这一点?当然,也许我可以使用getFloat()然后转换为整数....但我不知道它是否是一种优雅的方式来做...所以任何想法?

更新:Oooppssss我犯了一个错误.它是:int quantity = typedValue.getFloat();

代替:

int digitsBefore = typedValue.getFloat();
Run Code Online (Sandbox Code Playgroud)

Mar*_*rko 43

为什么不在res/integers.xml中存储整数

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="quantity_length">12</integer>
</resources>
Run Code Online (Sandbox Code Playgroud)

并访问代码中的值

int myInteger = getResources().getInteger(R.integer.quantity_length);
Run Code Online (Sandbox Code Playgroud)

或者用XML

android:maxLength="@integer/quantity_length"
Run Code Online (Sandbox Code Playgroud)

  • 是的,它旨在存储整数,尺寸用于存储尺寸,如**dp**,**sp**等. (2认同)