Android RecyclerView加载Double数组生成按钮却显示为空问题求助
问题修复方案
核心原因
RecyclerView必须搭配LayoutManager才能正常渲染子项,你当前没有给RecyclerView设置任何LayoutManager,系统无法确定子项的排列规则,所以不会触发Adapter的任何生命周期方法,也不会渲染内容,这就是你Adapter里的makeToast没有被调用、列表始终为空的根本原因。
修复步骤
在ResultPage类的onCreate方法中,给resRecyclerView设置LayoutManager即可,示例代码如下:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result_page) resRecyclerView = findViewById(R.id.test_recycler_view_one) // 新增这一行,设置线性排列的LayoutManager resRecyclerView.layoutManager = LinearLayoutManager(this) val ListToSend = intent.extras?.getDoubleArray(LIST)!!.toList().toDoubleArray() resRecyclerView.adapter = ResultsAdapter(this,ListToSend) // 其余原有代码不变 }
如果你需要网格布局或者横向排列,也可以替换成GridLayoutManager、StaggeredGridLayoutManager等对应实现。
可选优化建议
- 你已经导入了ViewBinding相关的类,可以直接使用Binding加载布局,不需要手动调用
findViewById,减少空指针风险。 - 按钮布局文件的根节点不需要嵌套GridLayout,直接把Button作为根布局即可,减少不必要的视图层级。
内容的提问来源于stack exchange,提问作者Vaishnav Kanhirathingal
相关产品推荐
相关产品推荐

