问题
I would like to make a RecyclerView
having differents elements per line depending on a boolean in the adapter.
In my app, you have some banknote and coins. I have to put all in a RecyclerView
. First of all I want to show the banknote (2 per 2) and after the coins (4 per 4)
like this :
This is how I want the result look like :
This is my Adapter
class MoneyAdapter(private val money_list: ArrayList<Money>) : RecyclerView.Adapter<MoneyAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MoneyAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.item_money, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: MoneyAdapter.ViewHolder, position: Int) {
money_map.put(money_list[position].value, 0)
holder.bindItems(money_list[position])
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(money: Money) {
// if (money.isCoin) I would like to put it on a 4 element per line
}
}
}
override fun getItemCount(): Int {
return money_list.size
}
}
This is where I declar emy RecyclerView :
recycler_money.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
recycler_money.adapter = MoneyAdapter(getMoneyList(PrefsModel.currency)
I was searching a lot of examples but it's always with differents col/row using StaggeredGridLayoutManager
and I want only change the number of elements by line (2 or 4) directly on the Adapter
.
回答1:
I found the solution thanks to @Gautam :
val l = GridLayoutManager(context, 4)
l.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
if (getMoneyList(PrefsModel.currency)[position].type == MONEY_PIECE)
return 1
else
return 2
}
}
recycler_money.layoutManager = l
来源:https://stackoverflow.com/questions/49190322/recyclerview-with-various-elements-in-the-same-line