将链接存储在字符串中的最佳实践

时间:2017-12-08 07:53:57

标签: android string

当我需要在简单的浏览器中打开链接时,我有两个选项来使用应用程序的链接。

而是将其保存在strings.xml文件中

<string name="link_openBrowser_calendar" translatable="false">/schedule/</string>

看起来很难看,或者只是将它作为

保存在Constants.java文件中
final static final String linkSchedule = "/schedule/";

在某些情况下,我有很多这样的链接,需要额外的参数

<string name="link_openBrowser_account_byId" translatable="false"> 
    /accounts/account/?id=%1$s 
</string>

甚至更多参数

<string name="view_meeting_time_inOneDay_period">%1$s at \n%2$s – %3$s</string>

当需要翻译部分字符串时很有用,但在代码中它看起来非常庞大且难以阅读。

String time = mEvent.isAllDay() ? getString(R.string.view_meeting_time_inOneDay_allDay, isTodayStr)
                : getString(R.string.view_meeting_time_inOneDay_period, isTodayStr, startStr, finishStr);

这些方法中的哪一种在可扩展性,性能或仅仅是清晰度方面更有效率?我相信在某些方面,存储这些链接的地方很重要,虽然它们并不是一直使用而只需要“随时随地”,而是将内存存储为static

2 个答案:

答案 0 :(得分:0)

如果您的应用程序需要具有可选文本样式和格式的文本字符串,strings.xml很方便。例如,您可以使用它将字符串翻译成其他语言。 Android会查看用户首选项并从正确的本地化文件夹中选择strings.xml文件(values是基本文件,values-xx代表其他语言)。另一方面,您应该为需要在全局范围中使用的其他字符串使用单独的类(例如,Constants.java)。在Constants.java中定义那种常量字符串是最佳做法。

答案 1 :(得分:0)

我发现在.gradle文件中存储代表API或服务器链接的链接的资源字符串要好得多。这里的想法是在开发阶段我们想要使用 debug / dev API链接测试我们的API或其他任何东西,所以在.gradle文件中设置它我们可以为每个创建不同的字符串构建类型。

android {
  ...
  buildTypes {
    release {
      buildConfigField("String", "API_URL", "\"https://api.release\"")

      // These values are defined only for the release build, which
      // is typically used for full builds and continuous builds.
      buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
      resValue("string", "build_time", "${minutesSinceEpoch}")
      ...
    }
    debug {
      buildConfigField("String", "API_URL", "\"https://api.debug\"")

      // Use static values for incremental builds to ensure that
      // resource files and BuildConfig aren't rebuilt with each run.
      // If they were dynamic, they would prevent certain benefits of
      // Instant Run as well as Gradle UP-TO-DATE checks.
      buildConfigField("String", "BUILD_TIME", "\"0\"")
      resValue("string", "build_time", "0")
    }
  }
}

...

相关问题