gpt4 book ai didi

list - 如何在 Kotlin 中将项目添加到列表中?

转载 作者:行者123 更新时间:2023-12-02 11:40:37 25 4
gpt4 key购买 nike

我正在尝试将元素列表添加到字符串列表中,但我发现 Kotlin没有像 java 这样的添加功能所以请帮助我如何将项目添加到列表中。

class RetrofitKotlin : AppCompatActivity() {

var listofVechile:List<Message>?=null
var listofVechileName:List<String>?=null
var listview:ListView?=null
var progressBar:ProgressBar?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_retrofit_kotlin)

listview=findViewById<ListView>(R.id.mlist)
var apiInterfacee=ApiClass.client.create(ApiInterfacee::class.java)
val call=apiInterfacee.getTaxiType()
call.enqueue(object : Callback<TaxiTypeResponse> {

override fun onResponse(call: Call<TaxiTypeResponse>, response: Response<TaxiTypeResponse>) {

listofVechile=response.body()?.message!!
println("Sixze is here listofVechile ${listofVechile!!.size}")
if (listofVechile!=null) {
for (i in 0..listofVechile!!.size-1) {

//how to add the name only listofVechileName list

}
}
//println("Sixze is here ${listofVechileName!!.size}")
val arrayadapter=ArrayAdapter<String>(this@RetrofitKotlin,android.R.layout.simple_expandable_list_item_1,listofVechileName)
listview!!.adapter=arrayadapter

}
override fun onFailure(call: Call<TaxiTypeResponse>, t: Throwable) {

}
})
}
}

最佳答案

更惯用的方法是使用 MutableList而不是专门 ArrayList .您可以声明:

val listOfVehicleNames: MutableList<String> = mutableListOf()

并以这种方式添加它。或者,您可能希望更喜欢不变性,并将其声明为:
var listOfVehicleNames: List<String> = emptyList()

在您的完成块中,只需重新分配它:
listOfVehicleNames = response.body()?.message()?.orEmpty()
.map { it.name() /* assumes name() function exists */ }

关于list - 如何在 Kotlin 中将项目添加到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55488291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com