【问题标题】:Android resource: array of strings with key/id?Android资源:带有键/ id的字符串数组?
【发布时间】:2020-06-29 23:21:39
【问题描述】:

我需要创建一个Spinner(或公开的下拉菜单),用户可以在其中选择持续时间,在本例中为天数。类似的东西

one day
two days
three days

稍后我想翻译这个应用程序,所以我不能在我的代码中使用显示的文本,例如像

if(item.equals("one day"))

对于英语以外的其他语言将失败。

所以我想要一个“显示值”(向用户显示的内容,例如“一天”)和一个技术 ID/密钥,例如“1DAY”。 Android 资源文件如何做到这一点?

我终于想要这样的东西了:

<!-- give a technical key 1DAY/2DAYS/3DAYS etc to the items -->
<!-- this is just a mockup - how could something like this be really done? -->
<string-array name="duration">
    <item key="1DAY">@string/one_day</item>
    <item key="2DAYS">@string/two_days</item>
    <item key="3DAYS">@string/three_days</item>
    <!-- and so on -->
</string-array>

<!-- these strings could be translated -->
<string name="one_day">one day</string>
<string name="two_days">two days</string>
<string name="three_days">three days</string>

【问题讨论】:

    标签: android arrays resources spinner translation


    【解决方案1】:

    if(item.equals(getResources().getString(R.string.one_day)))

    这将从正确的语言中检索正确的字符串值。

    参考this post

    【讨论】:

      【解决方案2】:

      另一个选择是使用属性标签。标记在你的视图上保存一个键,例如,你可以像这样创建一个枚举:

      enum class Days {
        ONE,
        TWO,
        THREE
      }
      

      并映射您的标签:

      fun map(days: Days): Int =
          when(days) {
            ONE -> R.string.one
            TWO -> R.string.two
            else -> R.string.x
          }
      

      所以,传递给视图的数据是:

      val exampleDays = Days.ONE
      val textId = map(exampleDays)
      
      your_view.text = getString(textId)
      your_view.tag = exampleDays
      

      要恢复值,只取标签:

      val tag = your_view.tag as Days // cast in Kotlin
      if (tag == Days.ONE) 
      

      使用这种方法可以避免重复的字符串,并且是使用干净架构的好方法。

      【讨论】:

        猜你喜欢
        • 2016-10-09
        • 1970-01-01
        • 2015-02-08
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 2017-04-16
        • 2011-05-24
        • 1970-01-01
        相关资源
        最近更新 更多