Why does TextView cannot display formatted text referred from android resources?

323 views Asked by At

I am trying to display a text that i set in TextView. I have already assigned a string in strings.xml with the name operator_mixed

Strings.xml

<string name="operator_mixed">%d  %s %d  %s %d</string>

And in my initialize.java file i tried to refer to this string, but it doesn't display anything.However when i try to display text without any formatting it kinda works ,but i know concatenating strings in textview is not preferable.

Initialize.java

textview.setText(getString(R.string.operator_mixed, a1, operator1, a2, operator2, a3));

Where a1, a2, a3 are integers and operator1, operator2 are strings.

Is there any problem with my code?

3

There are 3 answers

0
Ramu On BEST ANSWER

I figured it out. I just need to pass a Context like this:

textview.setText(c.getResources().getString(R.string.operator_mixed, a1, operator1, a2, operator2, a3))

here c is the context of MainActivity.

2
Mehul Kabaria On

Try with below

<string name="operator_mixed">%d  %s %d  %s %d</string>
textview.setText(String.format(getString(R.string.operator_mixed),a1,operator1,a2,operator2,a3)));

You have to use String.format()

1
Ajay Mehta On

I just tried this code in my app.

string.xml: (Same as yours)

<string name="operator_mixed">%d  %s %d  %s %d</string>

MyActivity.java

int a1 = 10;
int a2 = 20;
int a3 = 30;
String operator1 = "Operator 1";
String operator2 = "Operator 2";

my_txt_title.setText(getResources().getString(R.string.operator_mixed, a1, operator1, a2, operator2, a3));

It's working fine.

enter image description here