Evo*_*sub 1 variables android textview
我尝试将一个或多个变量放入TextView. 例如:你好,我是一个“女孩”,我住在“波士顿”
我想知道最好的方法是什么:
- 可以直接在文件里做吗
layout?- 我可以只通过 Java 类来做到这一点吗?
- 我可以通过吗
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);
Run Code Online (Sandbox Code Playgroud)
它确实有效,但实际上我的TextView方法很长,所以我认为我的方法并不真正合适。
我可以给我一些建议吗?
使用 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);
Run Code Online (Sandbox Code Playgroud)
注意 - 避免在 TextView.setText() 中串联
| 归档时间: |
|
| 查看次数: |
3041 次 |
| 最近记录: |