无法从R.string获取字符串资源.* [英] Can't get string resource from R.string.*
问题描述
我有一个SQlite表,其中有两列_id
和name
.为了国际化,我将名称存储为R.string.today
现在,我想获取与R.string.today
关联的字符串资源:
I have a SQlite table with two columns _id
and name
. For internationalization purpose I store the name like R.string.today
Now I want to get string resource associated with R.string.today
:
String column = myCursor.getString(myCursor.getColumnIndex(MainDb.NAME));
int resId = getApplicationContext().getResources().getIdentifier(column, "strings", getApplicationContext().getPackageName());
String buttonText;
if (resId != 0)
{
buttonText = getApplicationContext().getString(resId);
} else
{
buttonText = "Resource is null!";
}
resId
始终为0.变量column
具有正确的值,我已经使用调试器对其进行了检查.我在resId
中尝试过不同的变体:
resId
is always 0. Variable column
have the right value, I've checked it with debugger. I've tried different variations in resId
:
- "string"而不是defType中的"strings".
- getResources的不同变体,例如Resources.getSystem()...
- getPackageName()的不同变体
我做错了什么?
推荐答案
我认为应该是string
而不是strings
:
int resId = getApplicationContext().getResources()
.getIdentifier(column, "string", getApplicationContext().getPackageName());
还要检查column
的值是否表示strings.xml
中的标识符.
Check as well whether the value of column
dsignates an identifier in your strings.xml
.
这是一个很好的例子.
This is a nice example.
p.s.:代替R.string.today
,只需存储today
或从R.string.today
中提取store
.
p.s.: instead of R.string.today
just store today
or extract store
from R.string.today
.
Resources r = getResources();
r.getIdentifier("today", "string", getPackageName()));
r.getIdentifier("R.string.today", "string", getPackageName())); // doesn't work
r.getIdentifier("R.string.today".replaceAll(".*\\.", ""), "string", getPackageName()));
只有第一和第三工作.
这篇关于无法从R.string获取字符串资源.*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!