Home » Android » textview – Android setText / R.string / values

textview – Android setText / R.string / values

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am having trouble with setting text in a text view with format and multiple values.

holder.car.setText(R.string.mycar + lm.getCarName() + R.string.year + lm.getYear());

this is giving me ” 2143545 Camero 2143213 1977 “

I have tried few other “solutions” from the web

holder.car.setText(getString(R.string.mycar) + lm.getCarName() + getString(R.string.year) + lm.getYear());  << not work, getString undefine>>

I even tried String.valueOf(R.string.mycar); getResources().getText(R.String.mycar), still it didn’t work.

It would be great if someone can help me, thanks

How to&Answers:

Try this

holder.car.setText(getResources().getString(R.string.mycar));

Answer:

I think you’re trying to use parameters in your string.

Try this:

<string name="mycar">Car: %1$s Year: %2$s</string>

String mycar = getString(R.string.mycar);
mycar = String.format(mycar, lm.getCarName(), lm.getYear());

You should get:

Car: Camaro Year: 1977

Answer:

R.string.mycar and R.string.year are only IDs for resources. For this reason you get the numbers (IDs are numeric).

To get string from resources you need to use this construction:

String myCar = getResources().getString(R.string.mycar);

and now the myCar variable holds the string you put in strings.xml file under the mycar name.

the method getResources() belongs to Context. If you run your code outside an Activity, use the context instance to get the string, like this:

String myCar = context.getResources().getString(R.string.mycar);

Answer:

If you want to set your textview just a string from your string.xml file,

mytextview.setText(R.String.mycar);

If you want to set your textview with combination of some strings or integers, (better than first way)

int number=5;

mytextview.setText(getResources().getString(R.String.mycar) + " " +number + " " + getResources().getString(R.String.mysecondcar));

Answer:

Try this. If you’re fetching string in class without extending Activity Get using your Context

holder.car.setText(context.getResources().getString(R.string.mycar));

If you’re extending Activity

holder.car.setText(yourActivity.this.getResources().getString(R.string.mycar));

Hope this helps you..

Answer:

You have to retrieve your resources first, and the call the medthod getString(int), not getText, has you have put.

So, it should be:

getResources().getString(R.String.mycar);

Answer:

The R class contains kind of pointers to your ressources, so you can not directly use them, use getResources().getString(), as others say.