首页 > 解决方案 > Kotlin 制作所选项目的数组

问题描述

我有多个选择选项,我可以接收他们的 ID ,我需要的是制作这些 ID的数组以便将它们发送到服务器。

为什么我要制作我的数组数组?

因为我的主数组包含其他信息,我只需要提取(制作数组)id 而不是任何其他值,例如名称。

例子

我将选择 2 件商品并收到

id->1
name->one

id->2
name->two

然后我只需要制作这样的数组:

items[
    0->1
    1->2
]

代码

private fun printSelectedValue() {
  serviceAdapter?.getList()?.let {
    it.forEach { service ->
      Log.e("printSelectedValue", "selected service name:- ${service.service.name}")

      // I need array of this (service.id)
      Log.e("printSelectedValue", "selected service id:- ${service.id}")
    }
  }
}

PS:我需要能够在另一个函数中使用这个数组(id数组),所以最好在我的片段中有私有值以便在其他函数中访问它

任何想法?

标签: androidkotlin

解决方案


fun getSelectedIds(): Map<Int, Int> {
  val items = serviceAdapter?.getList() ?: return
  return items.withIndex().associate { (index, item) -> index to item.id }
}

推荐阅读