【问题标题】:Can't get string resource from R.string.*无法从 R.string.* 获取字符串资源
【发布时间】:2013-08-29 06:01:28
【问题描述】:

我有一个包含两列 _idname 的 SQlite 表。出于国际化目的,我将名称存储为 R.string.today 现在我想获取与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 中尝试了不同的变体:

  1. “字符串”而不是 defType 中的“字符串”。
  2. getResources 的不同变体,例如 Resources.getSystem()...
  3. getPackageName() 的不同变体

我做错了什么?

【问题讨论】:

  • 也许我没有得到你的 sn-p 但是......你为什么不直接使用int resId = getApplicationContext().getResources().getString(R.string.MYSTRING)
  • getResources() 需要活动上下文String s = getResources().getString(R.string.today)
  • 你试过只使用today而不是R.string.today吗?

标签: android android-resources


【解决方案1】:

我认为应该是string 而不是strings

int resId = getApplicationContext().getResources()
           .getIdentifier(column, "string", getApplicationContext().getPackageName());

还要检查column 的值是否指定了strings.xml 中的标识符。

This 是一个很好的例子。

p.s.:而不是 R.string.today,只需存储 today 或从 R.string.today 提取 store

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

只有第一个和第三个作品。

【讨论】:

  • 有趣!我晚上试试
  • 如何使用按钮 类似按钮 = getApplicationContext().getId(resId);
【解决方案2】:

试试这个

String str = context.getString(R.string.resId);

【讨论】:

  • resId 表示您的字符串。 R.string.yourString
最近更新 更多