从Android中的dimens.xml资源文件中获取整数值 [英] Get integer value from dimens.xml resource file in Android

查看:500
本文介绍了从Android中的dimens.xml资源文件中获取整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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" />

由于它的长度不仅会在UI xml文件中使用,而且还会在Java类以及其他一些地方使用,所以我想避免以后在更新此值时出现问题,因此我想将长度设置为集中在dimens.xml资源文件中,如下所示:

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>

我需要从Java类中读取此值,然后执行:

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);

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

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

    int digitsBefore = typedValue.getFloat();

因此我需要将其获取为整数....如何执行此操作?当然,也许我可以使用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?

更新: 糟糕,我做错了.它是: 整数数量= typedValue.getFloat();

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

代替:

int digitsBefore = typedValue.getFloat();

推荐答案

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

Why not store the integer in res/integers.xml

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

并访问代码中的值

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

或使用XML

android:maxLength="@integer/quantity_length"

这篇关于从Android中的dimens.xml资源文件中获取整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆