Java(Android):字符串模式中的数据

Java(Android):字符串模式中的数据,java,android,replace,Java,Android,Replace,我有一个带有字符串的TextView,需要在其中插入数据。 类似于:某些文本%d其他文本。 我不想在我的资料中有硬编码的文本。 有什么好的做法吗?如果您想将一些数据附加到TextView的现有数据,请使用以下方法: String finalText = (textView.getText().toString()).concat(" and new text here"); textView.setText(finalText); 希望这有帮助 编辑: 硬编码文本就是一个例子: 您可以简单地用

我有一个带有字符串的TextView,需要在其中插入数据。 类似于:某些文本%d其他文本。 我不想在我的资料中有硬编码的文本。 有什么好的做法吗?

如果您想将一些数据附加到TextView的现有数据,请使用以下方法:

String finalText = (textView.getText().toString()).concat(" and new text here");
textView.setText(finalText);
希望这有帮助

编辑:

硬编码文本就是一个例子:

您可以简单地用字符串替换它

String someText; //This can be retrieved from webservic or by any means you want.
String finalText = (textView.getText().toString()).concat(someText);
textView.setText(finalText);

如果要使用类似%d%s的模式格式化文本,可以将其用作:

String yourText = "default text"; // can be assigned runtime
Integer number= 2;
textView.setText(String.format("your data %s  %d", yourText, number)); 
您可以在这里使用任何保存所需值的字符串变量

希望能有帮助ツ

使用String.format方法格式化文本

String someText="some text";
String otherText="other text";
int value=100;
textView.setText(String.format("%s  %d %s", someText,value ,otherText));

将字符串存储在标签下的res文件夹中。 这将有助于你以后的翻译 然后在运行时将String.format与getString一起使用以形成字符串。

在活动中

String param1="something",param2="important";
int param3=233;

textView.setText(getResources().getText(R.string.tmpl, param1, param2,param3));
在您的strings.xml中

<string name="tmpl">here is %1$s %2$s which worth %3$d</string>

您可以将其设置为字符串文本=任何内容;textView.setTexttext;我已经提到,我不希望在代码中有硬编码文本。您可以使用任何保存字符串值的变量,这只是一个示例使用String.xml保存所有常量值。如果答案不正确,那么我就不明白你的问题。我说过我不想在代码中有硬编码文本。