Evan
Evan

Reputation: 880

Default text in TextView

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

Answers (4)

isamirkhaan1
isamirkhaan1

Reputation: 759

  1. Make a string resource in res/values/strings.xml

    <string name="time_prefix">"Elapsed Time: %s"</string>
    
  2. Get the resource string and concatenate your value with it

    String text = getResources.getString(R.string.time_prefix);
    String formattedText = String.format(text, X);
    
  3. Set the formatted text to textView

    mTimeTextView.setText(formattedText);
    

Note: if your value, X, is an integer then use %d

Upvotes: 1

brismith
brismith

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

Joseph Cobbinah
Joseph Cobbinah

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

Raymond Mutyaba
Raymond Mutyaba

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

Related Questions