使用带有参数的字符串资源(strings.xml)时出现问题

问题描述 投票:0回答:2

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

<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 给我这个错误:“格式字符串不是有效的格式字符串,因此不应将其传递给 string.format”

我正在使用最新版本的 Android Studio、最新版本的 Gradle 和

compileSdkVersion 23
    buildToolsVersion "23.0.3"
android android-resources android-lint
2个回答
0
投票

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

 lintOptions {
      abortOnError false
  }

您应该使用 ContextCompat 来获取字符串并连接它。


0
投票

您的字符串包含

String.format()
将尝试搜索和替换的参数。您的应用程序名称始终相同,并且不需要替换该 URL 参数。取出 URL 并单独格式化,然后将两者连接起来:

XML:

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

Java:

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);
© www.soinside.com 2019 - 2024. All rights reserved.