如何在Kotlin中从ArrayList中删除所有项

13

我在Kotlin中有一个数组列表,我想要将它里面的所有项目都移除,让它变成一个空数组以开始添加新的动态数据。我尝试过 ArrayList.remove(index)arrayList.drop(index),但都不起作用。

声明:

var fromAutoCompleteArray: List<String> = ArrayList()

这是我尝试的方法:

for (item in fromAutoCompleteArray){
        fromAutoCompleteArray.remove(0)
             }
我正在使用addTextChangedListener来根据用户的输入删除旧数据并添加新数据。
    private fun settingToAutoComplete() {
        val toAutoCompleteTextView: AutoCompleteTextView =
            findViewById<AutoCompleteTextView>(R.id.toAutoCompleteText)
        toAutoCompleteTextView.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                doLocationSearch(toAutoCompleteTextView.text.toString(), 2)

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                toAutoCompleteTextView.postDelayed({
                    toAutoCompleteTextView.showDropDown()
                }, 10)
            }

        })
        val adapter = ArrayAdapter(this, android.R.layout.select_dialog_item, toAutoCompleteArray)
        toAutoCompleteTextView.setAdapter(adapter)
        toAutoCompleteTextView.postDelayed({
            toAutoCompleteTextView.setText("")
            toAutoCompleteTextView.showDropDown()
        }, 10)
    }

这里是添加数据的函数:

    private fun doLocationSearch(keyword: String, fromTo: Number) {
        val baseURL = "api.tomtom.com"
        val versionNumber = 2
        val apiKey = "******************"
        val url =
            "https://$baseURL/search/$versionNumber/search/$keyword.json?key=$apiKey"
        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: okhttp3.Response) {
                val body = response.body?.string()
                println("new response is : $body")
                val gson = GsonBuilder().create()
                val theFeed = gson.fromJson(body, TheFeed::class.java)
                if (theFeed.results != null) {
                    for (item in theFeed.results) {
                        println("result address ${item.address.freeformAddress} ")
                        if (fromTo == 1) {
                            fromAutoCompleteArray = fromAutoCompleteArray + item.address.freeformAddress
                            println(fromAutoCompleteArray.size)
                        } else {
                            toAutoCompleteArray = toAutoCompleteArray + item.address.freeformAddress
                        }
                    }
                } else {
                    println("No Locations found")
                }


            }

            override fun onFailure(call: Call, e: IOException) {
                println("Failed to get the data!!")
            }
        })

    }

你看到的这行代码 println(fromAutoCompleteArray.size) 展示了是否已删除,它总是在增加。

此外,我尝试使用 clear() 函数但没有循环都不起作用:

fromAutoCompleteArray.clear()


你能发一下列表声明吗? - charles-allen
还有下面的代码,让你觉得它不是空的。 - charles-allen
1
@AjahnCharles 添加了有关该函数和TextView的完整细节。 - Ahmed Wagdi
2个回答

39
在 Kotlin 中,List 类型是不可变的。如果你想让你的列表发生改变,你需要将它声明为 MutableList
我建议修改这行:
var fromAutoCompleteArray: List<String> = ArrayList()

变成这样:

val fromAutoCompleteArray: MutableList<String> = mutableListOf()

然后您应该能够调用其中的任何一个:

fromAutoCompleteArray.clear()     // <--- Removes all elements
fromAutoCompleteArray.removeAt(0) // <--- Removes the first element

我也建议使用mutableListOf()而不是自己实例化ArrayList。Kotlin有明智的默认值,读起来更容易一些。大部分情况下它们最终都会执行相同的操作。

尽可能使用val而不是var更好。

更新: 感谢Alexey指出,应该使用val而不是var。


1
值得一提的是:在编程中,应该优先使用 val 而不是 var - Alexey Romanov
好观点@AlexeyRomanov。我很匆忙,没有推荐。已更新! - Todd

0
我不知道你如何声明ArrayList,但是可以按照以下方式完成。
var arrayone: ArrayList<String> = arrayListOf("one","two","three")

val arraytwo = arrayone.drop(2)

for (item in arraytwo) {
  println(item) // now prints all except the first one...
}

在你的情况下,请尝试这个

val arraytwo = fromAutoCompleteArray.toMutableList().apply { 
  removeAt(0)
}

第二个数组的需求是什么? - Ahmed Wagdi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接