如何在JavaAndroidStudio中使用String资源?
How to use the String resource in Java Android Studio?
我遇到了问题,Android Studio 提醒我使用 string.xml 设置文本。下面给了我提示:不要连接用 setText 显示的文本。使用带占位符的资源字符串。
public int points = 0;
public TextView tv_points;
tv_points.setText("Points: " + points);
好的,如果我将字符串 xml 与此代码一起使用,它不是我想要的:
<string name="points_string">Points: </string>
public int points = 0;
public TextView tv_points;
tv_points.setText((R.string.points_string) + points);
没有报错也没有提示,但是错了。我没有得到想要的设置点的效果。
您需要使用 strings.xml
格式化字符串,如下所示:
<string name="points_string">Points: %1$d</string>
那么你可以这样使用它:
tv_points.setText(getResources().getString(R.string.points_string, points));
我遇到了问题,Android Studio 提醒我使用 string.xml 设置文本。下面给了我提示:不要连接用 setText 显示的文本。使用带占位符的资源字符串。
public int points = 0;
public TextView tv_points;
tv_points.setText("Points: " + points);
好的,如果我将字符串 xml 与此代码一起使用,它不是我想要的:
<string name="points_string">Points: </string>
public int points = 0;
public TextView tv_points;
tv_points.setText((R.string.points_string) + points);
没有报错也没有提示,但是错了。我没有得到想要的设置点的效果。
您需要使用 strings.xml
格式化字符串,如下所示:
<string name="points_string">Points: %1$d</string>
那么你可以这样使用它:
tv_points.setText(getResources().getString(R.string.points_string, points));