gpt4 book ai didi

android - 如何将项目传递给 ViewHolder?

转载 作者:行者123 更新时间:2023-11-30 05:10:09 38 4
gpt4 key购买 nike

我是 Kotlin 的新手,我正在制作一款货币兑换应用。在适配器中,我想将一些项目传递到新 Activity 中。

 class AdapterC (val countryList: ArrayList<CountriesData>): RecyclerView.Adapter<AdapterC.ViewHolder>() {

override fun onCreateViewHolder(view: ViewGroup, position: Int): ViewHolder {

val v = LayoutInflater.from(view?.context).inflate(R.layout.country_list,view,false)
return ViewHolder(v)
}

override fun getItemCount(): Int {
return countryList.size
}

override fun onBindViewHolder(view: ViewHolder, position: Int) {

val country : CountriesData=countryList.toTypedArray()[position]
view?.textViewName.text=country.name

/*
Old code in which i can accese to items
view.itemView.setOnClickListener{
var name = country.name
var id = country.id
}
*/

}


class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){

val textViewName= itemView.findViewById(R.id.TextViewCountry) as TextView

//New code that i found on the internet

init {

itemView.setOnClickListener{

val intent = Intent(itemView.context, CurrencyActivity::class.java)
itemView.context.startActivity(intent)

}
}
}

}

据我所知,将 setOnClickListener 放在 onBindViewHolder 中是一种不好的做法,我无法在其中启动新 Activity ,因此我在 Internet 上查找并找到了在 ViewHolder 类中启动新 Activity 的解决方案。但是现在我不知道如何将一个项目传递到新 Activity 中。

下面是数据类

data class CountriesData(val name :String,val id :String)

最佳答案

Kotlin 中的 RecyclerView 适配器

二手 Anko https://github.com/Kotlin/anko

Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java.

class StackAdapter(val context: Context, val countryList: ArrayList<CountriesData>) : RecyclerView.Adapter<StackAdapter.StackViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StackViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return StackViewHolder(view)
}

override fun getItemCount(): Int = countryList.size

override fun onBindViewHolder(holder: StackViewHolder, position: Int) {
holder.setUpViewHolder(countryList[position])
}

inner class StackViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val Name: TextView = itemView.txtView

fun setUpViewHolder(countries: CountriesData){
Name.text = countries.name
Name.setOnClickListener {
context.startActivity<CurrencyActivity>(COUNTRIES to countries)
}
}
}
}

如何在Activity中获取数据

    data = intent.getStringExtra(COUNTRIES)

注意 COUNTRIES 只是 Constants.kt 中的一个键

这就是您在 Kotlin 中的做法。 const val HEADER_USER_TYPE = "用户类型"

关于android - 如何将项目传递给 ViewHolder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53874574/

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