Kotlin Android开发报错:LayoutManager无伴生对象必须在此初始化
解决「Classifier 'LayoutManager' does not have a companion object」报错
问题原因
你写的 RecyclerView.LayoutManager = LinearLayoutManager(this) 是错误的写法:LayoutManager 是 RecyclerView 的内部抽象类,不是伴生对象,不能直接对这个类进行赋值操作。你需要给布局中具体的 RecyclerView 实例设置布局管理器,而非直接操作类本身。
解决步骤
- 确保你的
activity_main.xml布局文件里有带 id 的 RecyclerView 控件,示例如下:
<androidx.recyclerview.widget.RecyclerView android:id="@+id/newsRecyclerView" android:layout_width="match_parent" android:layout_height="match_parent" />
- 在 MainActivity 中先获取 RecyclerView 实例,再给它设置 LinearLayoutManager,修改后的代码如下:
package com.example.newsshare import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 获取布局里的RecyclerView实例 val recyclerView = findViewById<RecyclerView>(R.id.newsRecyclerView) // 给实例设置LinearLayoutManager布局管理器 recyclerView.layoutManager = LinearLayoutManager(this) } }
额外说明
如果后续想简化视图查找操作,可以学习使用 Android 的视图绑定功能,它能自动生成布局对应的绑定类,避免手动写 findViewById 的麻烦,不过新手先掌握上述基础写法即可。
内容的提问来源于stack exchange,提问作者Dhiraj Gilda
相关产品推荐
相关产品推荐

