Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the String resource in Java Android Studio?

I´ve got the problem, that Android Studio reminds me to use the string.xml for set the text. The following gives me the hint: Do not concatenate text displayed with setText. Use resource string with placeholders.

public int points = 0;
public TextView tv_points;
tv_points.setText("Points: " + points);

Okay if i use the string xml with this code it does not what i want:

<string name="points_string">Points: </string>    

public int points = 0;
public TextView tv_points;
tv_points.setText((R.string.points_string) + points);

It brings no error and no hint, but is wrong. I do not get the wanted effect to set the points.

like image 669
Chralt Avatar asked Oct 25 '25 23:10

Chralt


1 Answers

You need to format the string using strings.xml like this:

<string name="points_string">Points: %1$d</string>

Then you can use it like this:

tv_points.setText(getResources().getString(R.string.points_string, points));

like image 140
Pulak Avatar answered Oct 27 '25 13:10

Pulak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!