使用带参数的String资源(strings.xml)时出现问题

时间:2016-08-21 13:40:21

标签: android android-resources android-lint

我使用带参数的字符串,如下所示:

<string name="share_1">My Android device has reached %1$s points in the app: https://play.google.com/store/apps/details?id=%2$s</string>

String s = getString(R.string.share_1, result.getText().toString(), activity.getApplicationContext().getPackageName());

Lint给我这个错误:&#34;格式字符串不是有效的格式字符串所以不应该传递给string.format&#34;

我使用的是最新版本的Android Studio,最后一个版本的gradle和

compileSdkVersion 23
    buildToolsVersion "23.0.3"

谢谢

2 个答案:

答案 0 :(得分:0)

这只是lint错误。您可以在gradle中禁用lint错误

 lintOptions {
      abortOnError false
  }

你应该使用ContextCompat来获取字符串并将其连接起来。

答案 1 :(得分:0)

您的字符串包含String.format()将尝试搜索和替换的参数。您的应用名称始终相同,并且不需要替换URL参数。取出URL并单独格式化,然后连接:

<强> XML:

<string name="share_1">My Android device has reached %1$s points in the app:</string>

<强>爪哇:

String myAppUrl = String.format("https://play.google.com/store/apps/details?id=%s", activity.getApplicationContext().getPackageName());

String score = getString(R.string.share_1, result.getText().toString())

String toBeDisplayed = String.format("%s %s", score, myAppUrl);