【问题标题】:Access resource string by string name in array通过数组中的字符串名称访问资源字符串
【发布时间】:2013-05-24 10:31:59
【问题描述】:

我正在尝试使用字符串数组从 XML 中获取资源,因为它当前处于循环中。

谁能告诉我如何做到这一点?

为了清楚起见,资源名称与数组字符串名称相同。

到目前为止我已经尝试过:

mMainEngine.mContext.getString(R.string.class.getField(Modification.ModicationNames[Current]).getInt(null)),

【问题讨论】:

  • 你有一个资源的名字,你想得到它的id吗?
  • 资源名称与数组字符串名称一致
  • 你需要this

标签: java android


【解决方案1】:

我没有误会你

int id = getResources().getIdentifier("name_of_resource","string", getPackageName());

是你需要的

【讨论】:

  • ModificationContainer 类型的方法 getPackageName() 未定义
  • 你需要一个上下文。 ModificationContainer 是一项活动吗?
  • 错误是“android.content.res.Resources$NotFoundException: String resource ID #0x0”,但字符串确实存在。
  • 用字符串代替 id。请参阅我的编辑。 getIdentifier("name_of_resource","string", getPackageName());
【解决方案2】:

例如,我正在访问 Drawable。您可以按如下方式从名称中获取 id

Resources res = context.getResources();
String strpckg = context.getPackageName();

int id = res.getIdentifier(iconName, "drawable", strpckg);

您还可以通过以下方式访问 Drawable:

Drawable drawable = res.getDrawable(id);

【讨论】:

  • 这是用于可绘制的,您可以对字符串或任何您想要的资源执行相同操作
猜你喜欢
  • 2022-07-22
  • 2017-02-22
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
相关资源
最近更新 更多