Search code examples
androidvariablestextview

Best way to put variables in a Textview?


I try to put one or more variables in a TextView. For exemple : Hello I am a "girl" and I live in "Boston"

I would like to know what is the best way to do it :

  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 ?

For now i do it like this :

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);

It works yes but in fact my TextView are very long so I don't think my way is really appropriate.

Can i have some advice ?


Solution

  • 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);
    

    Note - Avoid concatenation in TextView.setText()