我正在使用带有spancount 2的gridlayout,但是我想在每10个项目之后显示spancount 1

qlzsbp2j  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(313)
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);

recyclerView.setLayoutManager(gridLayoutManager);

我正在尝试,但这是不工作,没有任何错误,我到处找,但找不到任何人可以帮助。

if(gridLayoutManager.getItemCount() == 10){gridLayoutManager.setSpanCount(1);}else{gridLayoutManager.setSpanCount(2);
}
yqkkidmi

yqkkidmi1#

val gridLayoutManager = GridLayoutManager(this, 2)
gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int {
        return if (position % 10 == 0) 2 else 1
    }
}
rv.layoutManager = gridLayoutManager

我用的是kotlin,你可以用java重写它,只要用java中的gridlayoutmanager.setPansizeLookup()方法就可以了。注意,spansize表示重量,而不是计数。

t9eec4r0

t9eec4r02#

这是我的代码的一部分,每行设置3个项目,每9个项目后设置spancount 1
您可以将此kotlin代码转换为java并设置约束

private val SHOP_TYPE = 1
private val AD_TYPE = 2

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    if(viewType == SHOP_TYPE) {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_shop_home, parent, false)
        return ShopViewHolder(view)
    }
    else {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_ad_search, parent, false)
        return AdsViewHolder(view)
    }
}

override fun getItemCount(): Int {
    return shopsList.size + adsList.size
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val countAds = (position + 1) / 10
    val indexAd = if(((position + 1) / 10) - 1 < 0) 0 else ((position + 1) / 10) - 1
    val isLastOne = (position + 1) == (shopsList.size + adsList.size)
    if((position + 1) % 10 == 0 || isLastOne) {
        val adsHolder = holder as AdsViewHolder
        adsHolder.bind(adsList[indexAd], adsClickListener)
    }
    else {
        val shopHolder = holder as ShopViewHolder
        shopHolder.bind(shopsList[position - countAds], shopClickListener)
    }
}

override fun getItemViewType(position: Int): Int {
    if((position + 1) % 10 == 0 || (position + 1) == (shopsList.size + adsList.size))
        return AD_TYPE
    return SHOP_TYPE
}

open class ViewHolder(view: View): RecyclerView.ViewHolder(view){
}

class ShopViewHolder(view: View): ViewHolder(view) {

}

class AdsViewHolder(private val view: View): ViewHolder(view) {

}

你在你的碎片/活动上设置了这个代码

private fun setRecyclerView() {
    searchAdapter = SearchAdapter(shopsList, adsList)
    val gridLayoutManager = GridLayoutManager(requireContext(), 3)
    gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            if((position + 1) % 10 == 0 || (position + 1) == (shopsList.size + adsList.size))
                return 3
            return 1
        }
    }
    rootView.rvSearch.layoutManager = gridLayoutManager
    rootView.rvSearch.setHasFixedSize(true)
    rootView.rvSearch.adapter = searchAdapter
}

相关问题