0

I have a TextView with a string where I need to insert data.
Something like: "some text %d other text".
I don't want to have a hardcoded text in my sources.
Are there any good practices for that?

4
  • You can set it as String text ="whatever it is"; textView.setText(text); Commented Dec 12, 2014 at 4:24
  • I've mentioned that I don't want to have a hardcoded text in my code. Commented Dec 12, 2014 at 4:38
  • you can use any variable which holds String value, this was just an example Commented Dec 12, 2014 at 4:43
  • Use String.xml to hold all the constant values. If it was not the right answer, then I didn't get your question. Commented Dec 12, 2014 at 4:48

5 Answers 5

1

In your Activity,

String param1="something",param2="important";
int param3=233;

textView.setText(getResources().getText(R.string.tmpl, param1, param2,param3));

In your strings.xml

<string name="tmpl">here is %1$s %2$s which worth %3$d</string>
Sign up to request clarification or add additional context in comments.

Comments

1

Store your string just as said in the res folder under <string></string> tag. This will help you in translation later Then use String.format() with getString() to form the String at runtime.

Comments

0

If you want to append some data to existing data of TextView then use this:

String finalText = (textView.getText().toString()).concat(" and new text here");
textView.setText(finalText);

Hope this helps.

EDIT:

Hardcoded text was an example:

You can simply replace it by String.

String someText; //This can be retrieved from webservic or by any means you want.
String finalText = (textView.getText().toString()).concat(someText);
textView.setText(finalText);

1 Comment

I've mentioned that I don't want to have a hardcoded text in my code.
0

If you want to format text with pattern like %d %s, you can use it as :

String yourText = "default text"; // can be assigned runtime
Integer number= 2;
textView.setText(String.format("your data %s  %d", yourText, number)); 

You can use any String variable here which holds your desired value.

Hope it helps ツ

Comments

0

Use String.format() method for formatting text

String someText="some text";
String otherText="other text";
int value=100;
textView.setText(String.format("%s  %d %s", someText,value ,otherText));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.