Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/212.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 按键访问字符串资源_Android - Fatal编程技术网

Android 按键访问字符串资源

Android 按键访问字符串资源,android,Android,我试图使用xml资源文件来存储某些值的映射。然后,在我的应用程序中,当我想要获取它们的值时,我想要一种只通过键访问xml文件中的值的方法。问题是我事先不知道钥匙。有一些逻辑计算要获取的键,然后我必须获取该键的值。例如: switch(id) { case 0: key = hello; break; case 1: key = world; break; } public Str

我试图使用xml资源文件来存储某些值的映射。然后,在我的应用程序中,当我想要获取它们的值时,我想要一种只通过键访问xml文件中的值的方法。问题是我事先不知道钥匙。有一些逻辑计算要获取的键,然后我必须获取该键的值。例如:

    switch(id) {
       case 0:
         key = hello;
         break;
       case 1:
         key = world;
         break;
    }
public String getStringById(id) {
    switch(id) {
       case 0:
         return getString(R.id.hello); break;
       case 1:
         return getString(R.id.world); break;
    }
}

现在,我想访问存储在xml文件中的这些键的值。我怎样才能做到这一点?我不想使用SharedReference,也不能准确地使用resources.getString(R.string.\ux),因为我事先不知道密钥。

只需使用R.id即可。在交换机内,例如:

    switch(id) {
       case 0:
         key = hello;
         break;
       case 1:
         key = world;
         break;
    }
public String getStringById(id) {
    switch(id) {
       case 0:
         return getString(R.id.hello); break;
       case 1:
         return getString(R.id.world); break;
    }
}
但是,如果不能这样做,则可以获得字符串的
int
id,如下所示:

int text_id = YourActivity.this.getResources()
    .getIdentifier("hello", "string", YourActivity.this.getPackageName());
因此,您的代码将如下所示:

String key = "";
switch(id) {
   case 0:
     key = hello;
     break;
   case 1:
     key = world;
     break;
}
int text_id = YourActivity.this.getResources()
    .getIdentifier(key, "string", YourActivity.this.getPackageName());
String text = YourActivity.this.getResources()
    .getString(text_id);
return text;

如果我理解正确,您只有一个字符串“key”来获取资源

getResources().getString(
        getResources().getIdentifier(key, "string", getPackageName()))

开关就是一个简单的例子。我真正的用例是我有一个带键的dic t,我希望值来自一个资源文件。因此,我检查(userInput==dict.containsKey(userInput))->是否获取资源xmlentry@JohnBaum看看第二个例子