【问题标题】:How do I set text of TextView to a string resource? (Java for android)如何将 TextView 的文本设置为字符串资源? (适用于安卓的 Java)
【发布时间】:2015-02-13 16:53:52
【问题描述】:

我想将TextView 组件的文本更改为我已经在strings.xml 中创建的另一个文本。当应用程序启动时,显示的文本存储在strings.xml 中,名称为“help0”。我想以编程方式将其设置为名称为“help00”的字符串,方法是在名称的 and 处放置另一个“0”。到目前为止,我已经编写了这段代码:

String help = "0";
help = help + "0";
final TextView help = (TextView) findViewById(R.id.help);
help.setText("@string/help" + help);

但是,当我运行应用程序时,文本变为“@string/help00”,而不是我存储在strings.xml 中的help00 下的文本。

我该如何解决这个问题?

【问题讨论】:

  • 你的 strings.xml 文件中是否声明了 help00?
  • 你想要文本末尾的“0”还是想要获取“help0”的字符串资源id?
  • @codeMagic,orb 太混乱了,不是吗?
  • 是的,它已被声明。应用启动时,显示来自strings.xml的help0的值,我想将其更改为help00的值(来自strings.xml)

标签: java android textview


【解决方案1】:

因为您已将字符串资源 id 与普通字符串 help 连接起来,所以它作为 String 工作。您必须从 android 资源中获取第一个资源字符串,然后需要与本地字符串变量连接,例如,

help.setText(getResources().getString(R.string.help)+help);

我怀疑,如果您正在寻找动态字符串 id,您希望字符串资源 id 已经存在 id 和 '0' 附加到它,然后使用字符串从字符串获取 int 资源 id..

int resourceId = this.getResources().getIdentifier("@string/help" + help, "string", this.getPackageName());

然后

help.setText(resourceId);

【讨论】:

  • 我不想在显示的文本中添加一个“0”,而是在字符串的 ID 中添加一个 '0',就像我在 xml 中将它从 android:text="@string/help0" 更改为 android :文本“@string/help00”。有没有办法我可以做到这一点?更新:我看到了你的更新,谢谢:)
  • 我会在调用 setText 之前检查值 getIdentifier("help"+help, "string" this.getPackageName());
【解决方案2】:

试试这个

String help = "0";
final TextView tvHelp = (TextView) findViewById(R.id.help);
String yourString = getResources().getString(R.string.help);
tvHelp.setText(yourString +help)

【讨论】:

  • 我的问题是,我正在更改'stringId',所以在我更改它之后,我可以通过什么方式将其更改为其他内容? (正好在stringId的and处加一个'0',这样就变成了stringId0)
  • 这仍然只是在我遇到的显示文本中添加了一个“0”:(
【解决方案3】:

我相信strings.xml资源文件内容在运行时是不能编辑的。 现在我假设你的 strings.xml 文件中有以下内容

<resources>
    <string name="app_name">Application Name</string>
    <string name="help0">Text1</string>
    <string name="hellp00">Text2</string>
</resources>

如果您想将 TextView (id=@+id/textview) 上的文本从存储为“help0”的值更改为存储在“help00”中的值,请使用以下代码:

String text= getString(R.string.help00);
TextView myTextView = findViewById(R.id.textview);
myTextView.setText(text);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-15
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多