将变量放入 Textview 的最佳方式?

Best way to put variables in a Textview?

我尝试将一个或多个变量放在TextView中。 举个例子 : 您好,我是 "girl",我住在 "Boston"

我想知道最好的方法是什么:

  1. Can i do it directly in the layout file ?
  2. Can i do it only via Java Class ?
  3. Can i do it via values/styles.xml ?

现在我是这样做的:

String text1 = "Hello I am a ";
String text2 =" and I live in ";
String var1= preferences.getString("sex", "null");
String var2= preferences.getString("city", "null");
TextView Text = (TextView) findViewById(R.id.text);
Text.setText(text1 + var1 + text2 + var2);

它确实有效,但实际上我的 TextView 很长,所以我认为我的方法不是很合适。

有什么建议吗?

如果文本视图真的很长,那么您应该试试这个。

String var1= preferences.getString("sex", "null");
String var2= preferences.getString("city", "null");

Text.setText("Hello I am a"+var1+"\n"+"I live in"+var2);

这是在文本视图中显示文本的好方法

Use String.format(String format, Object... args)

String sex = preferences.getString("sex", "null");
String city = preferences.getString("city", "null");
String str = String.format("Hello I am a %s and I live in %s", sex, city);
TextView text = (TextView) findViewById(R.id.text);
text.setText(str);

注意 - 避免在 TextView.setText()

中连接