【问题标题】:Android uses wrong string ressourceAndroid 使用错误的字符串资源
【发布时间】:2024-08-06 10:30:02
【问题描述】:

有人知道我的问题的解决方案吗? 我为游戏中的 Shared Preferences 作为 Activity 制作了一个编辑器。有一个包含一个共享首选项的所有值的列表。但是当我为一个名为value_themetextView 写作时:

value_theme.setText(R.string.editor_div_value + settings_theme);

Android 使用来自其他活动的其他字符串资源。

当我写的时候

value_theme.setText(R.string.editor_div_value + "" + settings_theme);

应用程序将 TextView 文本设置为:21312309366。有谁知道如何解决这个问题?

【问题讨论】:

  • 当我使用 value_theme.setText("current value." + settings_theme);一切正常,但我想开发不止一种语言。
  • settings_theme 是共享首选项中的值
  • R.string.editor_div_value 只是一个数字,就像字符串值的索引。您需要获取字符串值,而不仅仅是引用索引。有关示例,请参阅@Bob 答案

标签: android string sharedpreferences


【解决方案1】:

使用这个:

value_theme.setText(context.getString(R.string.editor_div_value) + "" + settings_theme);

由于您要附加字符串,因此您错误地使用了错误的 setText 方法,该方法接受 CharSequence 并按原样设置为 TextView

或者另一种方法是进行字符串格式化。

<string name="editor_div_value">Your String value %1$s</string> 

在 Java 代码中获取字符串:

value_theme.setText(context.getString(R.string.editor_div_value, settings_theme));

【讨论】:

  • 你的意思是getApplicationContext()有上下文吗?
  • 你可以传递任何上下文。活动或应用程序上下文。
最近更新 更多