gpt4 book ai didi

android - 如何在Android Kotlin上增加动态布局?

转载 作者:行者123 更新时间:2023-12-02 13:29:24 27 4
gpt4 key购买 nike

我正在尝试在适配器上适应两种不同的布局,但是我没有成功,尝试了不同的方法,还在学习Kotlin语言,但是我需要创建此适配器,有人可以帮助我吗?

class AuctionAdapter(
private val context: Context?,
private val auctionList: List<Auction>,
private var viewType: Int
) : RecyclerView.Adapter<AuctionAdapter.AuctionHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AuctionHolder {

val itemView: View = if (this.viewType == 1) {
LayoutInflater.from(parent.context).inflate(R.layout.adapter_auction, parent, false)
} else {
LayoutInflater.from(parent.context).inflate(R.layout.adapter_auctions, parent, false)
}

return AuctionHolder(itemView)
}

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

class AuctionHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}

最佳答案

您缺少一些方法,这些方法应该实现,以便使RecyclerView知道要支持的不同行类型。

首先,让我们为您要支持的其他类型添加一个新的ViewHolder

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

其次,让我们将 getItemViewType添加到 AuctionAdapter
class AuctionAdapter ....

companion object {
const val SECTION_AUCTION = 0
const val SECTION_AUCTIONS = 1

@Retention(AnnotationRetention.SOURCE)
@IntDef(SECTION_AUCTION,
SECTION_AUCTIONS)
annotation class Section
}

@Section
override fun getItemViewType(position: Int): Int = auctionList[position].type.oridinal

最后,让我们修复 onCreateViewHolder
class AuctionAdapter(private val context: Context?, private val auctionList: List<Auction>, private var viewType: Int) : 
RecyclerView.Adapter<RecyclerView.ViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) {
SECTION_AUCTION -> AuctionHolder(LayoutInflater.from(parent.context).inflate(R.layout.adapter_auction, parent, false))
SECTION_AUCTIONS -> AuctionsHolder(LayoutInflater.from(parent.context).inflate(R.layout.adapter_auctions, parent, false))
else -> throw IllegalArgumentException("Unsupported view type $viewType")
}

关于android - 如何在Android Kotlin上增加动态布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62376662/

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