动态RecyclerView适配器接受任何列表

时间:2018-03-16 14:38:14

标签: android android-recyclerview kotlin generic-list

我有一个应用程序,根据所选的货币,我将列表传递给适配器,并根据作为参数传递的列表类型,我决定应该使用哪个模型类。

RecyclerView适配器

class CoinAdapter : RecyclerView.Adapter<CoinAdapter.MyViewHolder> {

private var coinList: List<Coin>? = null
private var coinINRList: List<CoinINR>? = null
private var coinEURList: List<CoinEUR>? = null
private var coinGBPList: List<CoinGBP>? = null

private var context: Context? = null

inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    var coinName: TextView
    var coinPrice: TextView

    init {
        coinName = view.findViewById(R.id.coin_title_text)
        coinPrice = view.findViewById(R.id.coin_price_text)
    }
}


constructor(coinList: List<Coin>?, context: Context?) {
    this.coinList = coinList
    this.context = context
}

constructor(coinList: List<CoinINR>?, context: Context?, second: String) {
    this.coinINRList = coinList
    this.context = context
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.coin_list_row, parent, false)

    return MyViewHolder(itemView)
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

    when (currencyUnit) {

        "USD" -> {

            val coin = coinList?.get(position)
            holder.coinName.text = coin?.name
            holder.coinPrice.text = coin?.price
        }

        "INR" -> {

            val coinINR = coinINRList?.get(position)
            holder.coinName.text = coinINR?.name
            holder.coinPrice.text = coinINR?.price
        }
    }
}

override fun getItemCount(): Int {

    when (currencyUnit) {

        "USD" -> return coinList?.size ?: 0
        "INR" -> return coinINRList?.size ?: 0

        else -> return coinList?.size ?: 0
    }

}
}

现在,我需要支持多种货币,因此代码正在成为样板。有什么方法可以让RecyclerView接受任何类型的列表,然后根据列表执行任务? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

我的建议是创建一个类Coin,它将成为所有其他货币对象的父级。

open class Coin(val name: String, val price: Float)

data class CoinINR(name: String, price: Float) : Coin(name, price)

比你的适配器只有一个List,你的onBindViewHolder方法将如下所示:

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

    with (coinList?.get(position)) {
            holder.coinName.text = it.name
            holder.coinPrice.text = it.price
    }
}