【问题标题】:Kotlin get string from resources by indexKotlin 通过索引从资源中获取字符串
【发布时间】:2021-07-01 22:57:17
【问题描述】:

我是 kotlin 的新手,我一直在尝试从我的资源中访问字符串数组。 我的 strings.xml 文件中有一个字符串数组,我想通过索引从中提取一个字符串。 我正在使用微调器来选择索引:

    override fun onItemSelected(
        parent: AdapterView<*>?,
        view: View?,
        position: Int,
        id: Long
    ) {
        titleTextView.text = R.array.content[position]
    }

当我尝试将位置参数作为数组索引传递时,我收到一条错误消息,告诉我我没有用于数组访问的 get 方法。

任何帮助将不胜感激。

【问题讨论】:

标签: android arrays kotlin


【解决方案1】:

首先从字符串资源中为数组声明一个实例变量:

private val contentArray by lazy { resources.getStringArray(R.array.content) }

在 onItemSelected 中使用position 获取如下值:

override fun onItemSelected(
    parent: AdapterView<*>?,
    view: View?,
    position: Int,
    id: Long
) {
    titleTextView.text = contentArray[position]
}

【讨论】:

    【解决方案2】:

    不要使用R.array.content,而是将整个字符串放入一个字符串数组中。

    val stringArray = getResources().getStringArray(R.array.(your array name));
    

    然后利用这个 stringArray 来访问使用位置的单个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 2011-01-25
      相关资源
      最近更新 更多