在android中连接2个字符串?

问题描述 投票:5回答:7

我正在用strings.xml在Toast中显示错误消息。

像这样mErrorMsgId=R.string.username_or_password_incorrectfull;

但是现在我需要将消息与R.string.add_selfhosted_blog合并,以避免翻译不一致。

阅读一些类似的问题,但无法弄清楚。

编辑:

我想在用户名或密码不正确的完整字符串中点击单词后连接nux_add_selfhosted_blog ...

<string name="username_or_password_incorrectfull">The username or password you entered is incorrect
 \- If you\'re a self hosted user, don\'t forget to tap **Add Self Hosted Site** and fill the URL field</string> 

<string name="nux_add_selfhosted_blog">Add self-hosted site</string>

我该如何实现?

java android string-concatenation string-formatting
7个回答
4
投票

您不能直接将R.string.username_or_password_incorrectfullR.string.add_selfhosted_blog连接起来,因为它们本身不是String实例,而是strings.xml中实际字符串的资源ID。您可以获取2个字符串,然后将它们正常连接。

类似这样的东西:

String string1 = getResources().getString(R.string.username_or_password_incorrectfull);
String string2 = getResources().getString(R.string.add_selfhosted_blog);

String combined = string1 + string2;

1
投票

方法makeText的第二个参数接受stringResId或仅接受String

例如:

String error = getResources().getString(R.string.username_or_password_incorrectful);
String error2 = getResources().getString(R.string.add_selfhosted_blog);
String conctString = error + " " + error2;
Toast.makeText(context, conctString, duration).show();

0
投票

只需从id的两个字符串中检索字符串,然后将+用作常规字符串,然后将结果字符串变量放入Toast中。

String messageToUser = getResources().getString(R.string.username_or_password_incorrectfull) +  getResources().getString(R.string.add_selfhosted_blog);
Toast.makeText(context, messageToUser, Toast.LENGTH_SHORT).show();

0
投票

如果您只想从String资源中连接这两个strings.xml,则可以通过此方法实现...

String errorMessage = getString(R.string.username_or_password_incorrectfull) + getString(R.string.add_selfhosted_blog);

然后在“ Toast”中显示简要的错误消息>

Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();

0
投票

您可以使用MessageFormat。


0
投票

您可以通过以下方式在另一个字符串的中间插入一个字符串,


0
投票

您可以使用我创建的该库来做到这一点:https://github.com/LikeTheSalad/android-string-reference它会根据您定义的模板字符串将您想要的所有字符串连接起来,然后在构建时生成最终的XML字符串。因此,对于您的情况,可以这样定义字符串:

© www.soinside.com 2019 - 2024. All rights reserved.