简体   繁体   中英

Android setText / R.string / values

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) 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

试试这个

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

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

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);

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);

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..

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));

R类包含指向你的资源的指针,所以你不能直接使用它们,使用getResources()。getString(),正如其他人所说。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM