【问题标题】:Android access XML constants actual value in codeAndroid 在代码中访问 XML 常量的实际值
【发布时间】:2014-05-12 09:57:18
【问题描述】:

在 XML 中,我定义了两个常量,如下所示

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="toast_x">10</integer>
    <integer name="toast_y">100</integer>
</resources>

但是当我在下面的代码中访问时

int xco = R.integer.toast_x;
int yco = R.integer.toast_y;

我分别得到奇怪的值 2131296257 和 2131296258

我知道那些是十六进制值。

但我只想访问实际值,即 10 和 100

请让我知道我怎样才能做到这一点......

【问题讨论】:

  • 您正在检索常量的 id,而不是它的

标签: java android xml constants


【解决方案1】:

如何获取整数资源值:

int xco = getResources().getInteger(R.integer.toast_x);
int yco = getResources().getInteger(R.integer.toast_y);

【讨论】:

    【解决方案2】:

    实际上,如果您尝试从外部 Activity 访问值,您也需要 Context

    class boo{
       public static void foo(Context con){
          int xco = con.getResources().getInteger(R.integer.toast_x);
          int yco = con.getResources().getInteger(R.integer.toast_y);
       }
    }
    

    上下文中的getResources()函数
    所以在这里从外部 Activity 访问价值很有趣

    class boo{
       public static int foo(Context con,int resId){
          return con.getResources().getInteger(resId);
       }
    }
    

    【讨论】:

    • @@NoXSaeeD,好的设计模式!
    【解决方案3】:

    在自己的标签中定义 toast_x 和 toast_y。

      <resources>
         <string name="toast_x">10</string>
         <string name="toast_y">100</string>
      </resources>
    

    现在来到你的java课 并将它们作为字符串读取,然后将它们转换为整数。

    String xcostr = getString(R.string.toast_x);
    int xco = Integer.valueOf(xcostr);
    
    String ycostr = getString(R.string.toast_y);
    int yco = Integer.valueOf(ycostr);
    

    【讨论】:

    • 如果你想要整数,为什么要把它保存为字符串!然后在那之后转换
    • 我想向提出这个问题的人说清楚,我猜他是一个 android 初学者。
    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 2012-11-25
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    相关资源
    最近更新 更多