Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 单击微调器时删除微调器内的项目_Android_Kotlin_Spinner_Coroutine - Fatal编程技术网

Android 单击微调器时删除微调器内的项目

Android 单击微调器时删除微调器内的项目,android,kotlin,spinner,coroutine,Android,Kotlin,Spinner,Coroutine,在MainActivity中,它有一个微调器,该微调器使用协同路由从服务器获取项目 代码 首先,我希望微调器默认显示为空。当用户单击微调器时,它将只显示两个项目,即“无”和“Ali” 我怎样才能做到这一点 到目前为止,我可以将空字符串设置为默认值,但当我单击时,微调器中有3个项目,它们是None、Ali和空字符串。要使您的字符串为默认值,但不在下拉列表中,您可以做的是提供您的适配器列表,该列表末尾包含空实体,但对于适配器计数,请在getCount方法中提供一个较少的计数。所以最后一个条目将在下拉

在MainActivity中,它有一个微调器,该微调器使用协同路由从服务器获取项目

代码

首先,我希望微调器默认显示为空。当用户单击微调器时,它将只显示两个项目,即“无”和“Ali”

我怎样才能做到这一点

到目前为止,我可以将空字符串设置为默认值,但当我单击时,微调器中有3个项目,它们是None、Ali和空字符串。

要使您的字符串为默认值,但不在下拉列表中,您可以做的是提供您的适配器列表,该列表末尾包含空实体,但对于适配器计数,请在getCount方法中提供一个较少的计数。所以最后一个条目将在下拉列表中被忽略

看看如何做到这一点:

val list = arrayListOf("None","Ali","Empty") // You can provide any type of list here
val adapter = object : ArrayAdapter<String>(context, itemLayout, list) {
    //Override getCount method and we reduce one count less when list is there, so that last entry would be ignored in dropdown.
    override fun getCount(): Int {
        val count = super.getCount()
        return if (count > 0) count - 1 else count
    }
}
your_spinner.adapter = adapter
your_spinner.setSelection(list.size-1) // We make our last list item as default entry
编辑O.p.:


但是我的列表是hashmap吗?您已经使用了这个语法list.keys.toTypedArray,对吗?像这样使用:list.keys.toMutableList.apply{this.addEmpty}我应该如何在我的代码中实现getCount方法?你是在列表的末尾添加空字符串吗?@Hoo然后是什么问题?
val list = arrayListOf("None","Ali","Empty") // You can provide any type of list here
val adapter = object : ArrayAdapter<String>(context, itemLayout, list) {
    //Override getCount method and we reduce one count less when list is there, so that last entry would be ignored in dropdown.
    override fun getCount(): Int {
        val count = super.getCount()
        return if (count > 0) count - 1 else count
    }
}
your_spinner.adapter = adapter
your_spinner.setSelection(list.size-1) // We make our last list item as default entry
spinnerName?.let { spn ->
    val adapterList = list.keys.toMutableList().apply { this.add("Empty") }
    spn.adapter = object : ArrayAdapter<String>(context, R.layout.spinner_item, adapterList) {
        //Override getCount method and we reduce one count less when list is there, so that last entry would be ignored in dropdown.
        override fun getCount(): Int {
            val count = super.getCount()
            return if (count > 0) count - 1 else count
        }
    }
    spn.setSelection(adapterList.size - 1)
}