如何在 Android Kotlin 上扩充动态布局?

How to inflate dynamic layout on Android Kotlin?

我试图在我的适配器上安装两种不同的布局,但我没有成功,我尝试了不同的方法,我仍在学习 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 充气,你应该做下一步

第一图书馆

compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+'

第二个容器

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rv"
    />

第三个适配器

public class Name extends RecyclerView.Adapter<RVAdapter.PersonViewHolder>{

第四组适配器

RVAdapter adapter = new RVAdapter(persons);
rv.setAdapter(adapter);

您缺少一些方法,您应该实施这些方法以使 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")
        }