无法从R.string获取字符串资源.* [英] Can't get string resource from R.string.*

查看:518
本文介绍了无法从R.string获取字符串资源.*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SQlite表,其中有两列_idname.为了国际化,我将名称存储为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:

  1. "string"而不是defType中的"strings".
  2. getResources的不同变体,例如Resources.getSystem()...
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆