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

Kotlin静态行RecyclerView仅垂直排列问题求助

问题解决:RecyclerView无法显示2列网格布局

我想要创建一个带有2列静态行的RecyclerView,但当前RecyclerView仅显示垂直单列布局,以下是相关代码(所有函数在Fragment的onViewCreated(...)中调用):

private fun setupRecyclerViews() {
    adapterDoSports = InterestAdapter(viewModel, "doSports")
    setupRecyclerView(adapterDoSports, binding.recyclerViewDoSports)
}

private fun setupRecyclerView(
    adapterInterest: InterestAdapter,
    recyclerViewInterest: RecyclerView
) {
    recyclerViewInterest.layoutManager = GridLayoutManager(requireContext(), 2)
    recyclerViewInterest.apply {
        adapter = adapterInterest
        layoutManager = LinearLayoutManager(activity)
    }
}

private fun setUpObservers() {
    viewModel.myUser.observe(viewLifecycleOwner) { response ->
        when(response) {
            is Resource.Success -> {
                response.data?.let { userResponse ->
                    adapterDoSports.differ.submitList(
                        userResponse.interests.doSports.keys.toMutableList())
                }
            }
            is Resource.Error -> {
                response.message?.let {
                    Log.e(TAG, "An error occurred: $it")
                }
            }
            is Resource.Loading -> {
                //TODO: some loading animation
            }
        }
    }
}

当前显示效果:
当前显示效果


问题原因

你在setupRecyclerView函数中先设置了GridLayoutManager(2列网格布局),但紧接着在apply代码块里又将layoutManager重新赋值为LinearLayoutManager,这直接覆盖了之前的网格布局配置,导致RecyclerView只能以垂直单列方式显示。

修正方案

删除apply块中覆盖布局管理器的代码,或者统一在apply里配置正确的布局管理器,修正后的代码如下:

private fun setupRecyclerView(
    adapterInterest: InterestAdapter,
    recyclerViewInterest: RecyclerView
) {
    recyclerViewInterest.apply {
        adapter = adapterInterest
        layoutManager = GridLayoutManager(requireContext(), 2)
    }
}

这样配置后,RecyclerView就会使用2列的网格布局管理器,实现你想要的静态行排列效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 08:18:32