You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin网格RecyclerView中库存为0的商品位置显示空白如何解决

问题根因

你当前的实现逻辑是将全量商品列表传入Adapter,仅在onBindViewHolder中隐藏零库存商品的内部子View,存在两个核心问题导致空白间隙:

  • getItemCount()返回的是全量商品的总数,零库存商品仍然会被分配一个独立的item占位
  • 仅隐藏了item内部的子控件,没有处理item根布局的占位属性,根布局仍会按照XML中预设的宽高占据空间

最优解决方案(推荐)

在接口返回数据后先过滤掉零库存商品,再将过滤后的有效列表传给Adapter,从根源上避免生成无效item:

修改Fragment中getpopular()方法

private fun getpopular() {
    LoadingUtils.showDialog(context, false)
    username = getUserId()
    val retrofitBuilder = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(BASE_L)
        .build()
        .create(ApiInterface::class.java)
    val retrofitData = retrofitBuilder.getpopularproductitems(90336, username!!)
    retrofitData.enqueue(object : Callback<productlist> {
        override fun onResponse(call: Call<productlist>, response: Response<productlist>) {
            Log.e("latest", "res-" + response.body())
            val responsebody: productlist = response.body()!!
            LoadingUtils.hideDialog()
            // 新增:过滤掉零库存商品
            val validProductList = responsebody.data.filter { 
                it.variants.firstOrNull()?.stock?.toInt() ?: 0 > 0 
            }
            // 传入过滤后的列表
            popularadapter = popularproductAdapter(frag, validProductList, addCart)
            // Grid布局要使用GridLayoutManager,按需求调整列数
            val gridLayoutManager = GridLayoutManager(context, 2)
            popularproductsRView.layoutManager = gridLayoutManager
            popularproductsRView.adapter = popularadapter
        }
        override fun onFailure(call: Call<productlist>, t: Throwable) {
            Log.d("MainError", "onFailure: " + t.message)
            LoadingUtils.hideDialog()
        }
    })
}

同步优化Adapter代码

  1. 删除onBindViewHolder中零库存逻辑里的所有隐藏View的代码,因为传入的已经是有效商品,不需要再做隐藏处理
  2. 移除holder.setIsRecyclable(false),这行代码禁用了RecyclerView的复用机制,会严重降低列表滑动性能
  3. 你原有代码中错误使用了LinearLayoutManager,Grid布局必须替换为GridLayoutManager,否则不会展示网格效果

备选方案(如需保留全量列表在Adapter中)

如果业务需要后续动态切换显示/隐藏零库存商品,可以在Adapter内部维护过滤后的列表:

class ProductListAdapter(
    val originalProductList: List<Data>,
    val context: Context,
    val addCart: AddCartListener,
    // 新增参数控制是否显示零库存商品
    private val showZeroStock: Boolean = false
) : RecyclerView.Adapter<ProductListAdapter.ProductListViewHolder>() {
    // 内部维护展示用的过滤列表
    private val showList = if (showZeroStock) {
        originalProductList
    } else {
        originalProductList.filter { it.variants.firstOrNull()?.stock?.toInt() ?: 0 > 0 }
    }
    override fun getItemCount(): Int = showList.size
    override fun onBindViewHolder(holder: ProductListViewHolder, position: Int) {
        val product = showList[position]
        // 后续绑定逻辑和原来一致,不需要再处理零库存隐藏
    }
    // 其他逻辑保持不变
}

内容的提问来源于stack exchange,提问作者SasidharanIOS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:36:04