【问题标题】:How can I access the items in my string-array resource within my Datasource class?如何访问我的数据源类中的字符串数组资源中的项目?
【发布时间】:2021-10-01 17:12:42
【问题描述】:

我正在尝试创建一个使用字符串作为键并将字符串数组作为值的映射。我正在我的 Datasource 类中创建这个地图。

我想用作键的字符串在 strings.xml 中声明,如下所示:

<string-array name="races">
        <item>Archfiend</item>
        <item>Asrai</item>
        <item>Blinkbeast</item>
        <item>Crogoblin</item>
        <item>Demonaga</item>
        <item>Dragonborn</item>
        <item>Dwarf</item>
        <item>Elf</item>
        <item>Fairy</item>
        <item>Gnome</item>
        <item>Grey</item>
        <item>Half-Dragon</item>
        <item>Half-Elf</item>
        <item>Half-Orc</item>
        <item>Half-Troll</item>
        <item>Halfling</item>
        <item>Haud</item>
        <item>Human</item>
        <item>Kodama</item>
        <item>Loralai</item>
        <item>Nekojin</item>
        <item>Parasite</item>
        <item>Satyr</item>
        <item>Slime</item>
        <item>Tiefling</item>
    </string-array>

例如,我想将字符串“Archfiend”映射到字符串数组“archfiend_subraces”。

<string-array name="archfiend_subraces">
        <item>Aerial</item>
        <item>None</item>
    </string-array>

我的数据源类如下​​所示:

package com.example.anime5echaractersheet.data

import android.content.res.Resources
import com.example.anime5echaractersheet.R

class Datasource {

    private val raceList: Array<String> = Resources.getStringArray(R.array.races)

    val subraceMap: Map<String, Int> = mapOf(
        raceList[0] to R.array.archfiend_subraces
    )
}

我无法使用 getStringArray(),我不知道为什么

我也尝试使用 getResources(),而不是 Resources,但这对我来说似乎也不可用。提前感谢您的帮助。

【问题讨论】:

    标签: arrays string android-studio kotlin resources


    【解决方案1】:

    您必须从 Context 实例中检索 Resources 的实例。您不能只使用类的名称来调用它的函数。因此,您的 DataSource 类在其构造函数中需要 ContextResources 参数。但是,我建议不要使用字符串资源作为键,因为如果您的应用程序有字符串的翻译并且用户更改了他们的语言设置,它将破坏您的应用程序。

    我建议在使用唯一键而不是文字值的 json 文件中定义所有类型和子类型列表。然后,您不必将所有这些硬编码的手动“连接”资源“连接”到彼此。如果您想例如添加或删除某个种族,它将使从单个 Json 文件编辑您的内容变得更加容易。例如:

    {
      "races" : [
        "archfiend" {
          "subraces" : [ "ariel", "none" ]
        },
        "asrai",
        ...
      ]
    }
    

    然后使用普通的 string 资源而不是 string-array 资源,这些资源使用 json 中的键作为名称。

    <string name="archfiend">Archfiend</string>
    <string name="ariel">Ariel</string>
    <string name="none">None</string>
    <string name="asrai">Asrai</string>
    

    在运行时,您可以使用这个辅助函数来检索实际的字符串:

    fun Context.resourceKeyToString(key: String): String =
        resources.getString(resources.getIdentifier(key, "string", packageName))
    

    这与您的问题无关。您可以查找有关在 Android 中使用 Json 的教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多