Reputation: 880
If I have a textview
like this:
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Elapsed Time: " />
I want my app to always display "Elapsed Time: ", followed by some value which I will update in my MainActivity. How can I do this without doing
mTimeTextView.setText("Elapsed Time: " + <some value here>);
each time?
Upvotes: 0
Views: 3520
Reputation: 759
Make a string resource in res/values/strings.xml
<string name="time_prefix">"Elapsed Time: %s"</string>
Get the resource string and concatenate your value with it
String text = getResources.getString(R.string.time_prefix);
String formattedText = String.format(text, X);
Set the formatted text to textView
mTimeTextView.setText(formattedText);
Note: if your value, X, is an integer then use %d
Upvotes: 1
Reputation: 696
Another way to do this is to use tokens in a string resource.
in strings.xml
<string name="elapsed_time">Elapsed time: %1$s</string>
in layout xml
<TextView android:text="@string/elapsed_time"
in code
mTimeTextView.setText(resources.getString(R.string.elapsed_time, <some value here>))
Upvotes: 4
Reputation: 46
Have you tried creating a custom TextView and overriding setText..? I'm not by my computer at the moment but will try it and send some code.
Upvotes: -1
Reputation: 950
You cannot unless you place two textviews together with no margin between them. The textview on the left will have the "Elapsed Time: " text and the textview on the right will have some value. Then, you only update the textview on the right.
Upvotes: 0