Android访问XML常量代码中的实际值

时间:2014-05-12 09:57:19

标签: java android xml constants

在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

我知道这些是HEX值。

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

请让我知道如何实现这一目标....

3 个答案:

答案 0 :(得分:6)

如何获取整数资源值:

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

答案 1 :(得分:2)

如果您尝试从外部活动

访问该值,实际上您也需要上下文
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()函数
所以这里有趣的是从外面的活动

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

答案 2 :(得分:0)

在自己的标记中定义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);