【问题标题】:Problems using String resources (strings.xml) with parameters使用带参数的字符串资源 (strings.xml) 时出现问题
【发布时间】:2016-09-28 06:23:39
【问题描述】:

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

<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


    【解决方案1】:

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

     lintOptions {
          abortOnError false
      }
    

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

    【讨论】:

    • ContextCompat 不再用于连接字符串。我使用常规的getString(resource, params)
    • 另外,这不是一个有效的解决方案,因为您只是隐藏 lint 错误。
    【解决方案2】:

    您的字符串包含String.format() 将尝试搜索和替换的参数。您的应用名称始终相同,并且不需要替换该 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 2020-06-10
      • 2023-03-30
      • 2016-10-09
      相关资源
      最近更新 更多