在Kotlin Fragment中创建ListView遇报错,求修复方案
解决Fragment中ListView无法正常工作的问题
你的代码在Fragment里报错主要有两个核心问题,对应修改方式如下:
问题1:Unresolved reference: findViewById
Fragment不能直接调用findViewById,必须依托视图对象来查找控件——Fragment的视图是在onCreateView执行完成后才生成的,正确的做法是把控件初始化逻辑放到onViewCreated回调中,通过方法参数里的view对象调用findViewById。
问题2:Type mismatch: inferred type is FragmentActivity? but Context was expected
ArrayAdapter需要的是有效且非空的Context对象:
- 不能直接传
this:Fragment本身不是Context类型 - 不能传
FragmentSearch:这是类名,不是可实例化的Context对象 - 推荐用
requireContext()获取Fragment关联的Context,它会确保Context非空,避免空指针风险
修正后的完整代码
把这段代码放到你的Fragment类的onViewCreated方法中:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 初始化数据列表 val carList = arrayListOf("2131231", "31312313123") // 通过view对象查找ListView val listView = view.findViewById<ListView>(R.id.listView) // 创建ArrayAdapter,传入正确的Context val arrayAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, carList) // 设置适配器 listView.adapter = arrayAdapter }
额外说明:你原来的代码里重复创建了两次ArrayAdapter,修正后只需要创建一次并设置给ListView即可,避免不必要的对象创建。
内容的提问来源于stack exchange,提问作者Utis
相关产品推荐
相关产品推荐

