在 Android 中使用多语言项目时,如何通过文本区分 Spinner 的选定项目?

How can I discriminate the selected item of a Spinner by its text when using multilanguage items in Android?

我试图通过其(多语言)文本来区分 Spinner 的选定项目。

这里是我默认的strings.xml内容:

<string-array name="spinner_items">
    <item>length</item>
    <item>weight</item>
    <item>temperature</item>
</string-array>

这是另一个strings.xml(意大利语)内容:

<string-array name="spinner_items">
    <item>lunghezza</item>
    <item>peso</item>
    <item>temperatura</item>
</string-array>

我以这种方式设置我的 Spinner 项目:

val items = resources.getStringArray(R.array.spinner_items)
spinner.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, items)

然后我添加项目选择监听器:

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

    override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        when(spinner.getItemAtPosition(position).toString()) {
            "length" -> actionLength()
            "lunghezza" -> actionLength()
            "weight" -> actionWeight()
            "peso" -> actionWeight()
            "temperature" -> actionTemperature()
            "temperatura" -> actionTemperature()
        }
    }

    override fun onNothingSelected(parent: AdapterView<*>) {}
}

一切正常,但问题是每次我添加新的语言环境时,我都必须记住在 when 块中添加特定的字符串翻译。 有没有更“动态”的方式来做到这一点?

只需使用 position:

    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

        override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
            when(position) {
              0 -> actionLength()
              1 -> actionWeight()
              2 -> actionTemperature()
            }
        }

        override fun onNothingSelected(parent: AdapterView<*>) {}
    }

在你的数组中使用:

<string-array name="spinner_items">
    <item>@string/length</item>
    <item>@string/weight</item>
    <item>@string/temperature</item>
</string-array>

我以前遇到过同样的问题,下面是我如何解决的。 通过为数组中的每个项目添加字符串资源名称来编辑 strings.xml 文件,例如:

默认strings.xml

<string name="length">length</string>
<string name="weight">weight</string>
<string name="temperature">temperature</string>

<string-array name="spinner_items">
    <item>@string/length</item>
    <item>@string/weight</item>
    <item>@string/temperature</item>
</string-array>

意大利语strings.xml

<string name="length">lunghezza</string>
<string name="weight">peso</string>
<string name="temperature">temperatura</string>

<string-array name="spinner_items">
    <item>@string/length</item>
    <item>@string/weight</item>
    <item>@string/temperature</item>
</string-array>

因此在您的代码中,您将拥有:

when(spinner.getItemAtPosition(position).toString()) {
    getString(R.string.length) -> actionLength()
    getString(R.string.weight) -> actionWeight()
    getString(R.string.temperature) -> actionTemperature()
}

希望对您有所帮助!