Evosub
Evosub

Reputation: 47

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 ?

Upvotes: 1

Views: 3847

Answers (2)

Palkesh Jain
Palkesh Jain

Reputation: 422

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

Upvotes: 5

Kalpesh A. Nikam
Kalpesh A. Nikam

Reputation: 323

If Text-view is really long then you should be try this.

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

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

This is good way Present Text in Text View

Upvotes: 0

Related Questions