【问题标题】:How to remove all items from ArrayList in kotlin如何从kotlin中的ArrayList中删除所有项目
【发布时间】:2019-09-28 13:57:07
【问题描述】:

我在 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()

【问题讨论】:

  • 能否请您发布列表声明
  • 还有下面这段代码让你觉得它不为空。
  • @AjahnCharles 添加了有关函数和文本视图的完整详细信息

标签: android kotlin


【解决方案1】:

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

更新:Vals 不是 vars,感谢您发现 Alexey

【讨论】:

  • 另外值得一提的是:更喜欢val 而不是var
  • 好点@AlexeyRomanov。我很着急,不建议这样做。更新了!
【解决方案2】:

我不知道你是如何声明 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)
}

【讨论】:

  • 第二个数组需要什么?
猜你喜欢
  • 2014-11-17
  • 1970-01-01
  • 2012-05-29
  • 2016-11-12
  • 1970-01-01
  • 2011-07-19
  • 2014-06-09
  • 1970-01-01
相关资源
最近更新 更多