RecyclerView在同一行中具有各种元素 [英] RecyclerView with various elements in the same line

查看:82
本文介绍了RecyclerView在同一行中具有各种元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个RecyclerView每行具有不同的元素,具体取决于适配器中的布尔值.

I would like to make a RecyclerView having differents elements per line depending on a boolean in the adapter.

在我的应用中,您有一些钞票和硬币.我必须将所有内容都放在RecyclerView中.首先,我想显示纸币(每2张2张),然后显示硬币(每4张4张) 像这样:

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 :

这是我的适配器

    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
    }

}

这是我声明RecyclerView的地方:

This is where I declar emy RecyclerView :

recycler_money.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
recycler_money.adapter = MoneyAdapter(getMoneyList(PrefsModel.currency)

我在搜索很多示例,但是使用StaggeredGridLayoutManager总是有不同的颜色/行,我只想直接在Adapter上按行(2或4)更改元素数.

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.

推荐答案

我通过@Gautam找到了解决方案:

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

这篇关于RecyclerView在同一行中具有各种元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆