Android Kotlin项目中ListView未调用自定义Adapter的getView()问题
Android Kotlin:ListView自定义Adapter的getView()未调用问题排查与解决
问题现象
- ListView绑定自定义ListAdapter后,日志显示
getCount()返回正确的非0数值,但getView()、getItem()等方法完全未被触发 - 尝试通过
post方式设置Adapter,问题仍未解决
问题根源
在DashboardFragment的onCreateView()方法中存在布局实例不匹配的核心错误:
- 先通过
DashboardBinding.inflate()生成了布局实例root - 又通过
inflater.inflate(R.layout.dashboard, container, false)生成了另一个独立的布局实例view,并在该实例中找到ListView完成Adapter绑定 - 最终返回的是未绑定Adapter的
root实例,导致实际显示的布局与绑定了Adapter的ListView并非同一个对象,绑定逻辑完全失效
修正方案
统一使用ViewBinding(推荐方案),确保操作的布局实例与返回实例一致。修正后的onCreateView()代码如下:
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = DashboardBinding.inflate(inflater, container, false) val root: View = binding.root val policy = ThreadPolicy.Builder().permitAll().build() listReturned.add(ApiRes(content = "testing", author="around", timestamp=12, important=true)) StrictMode.setThreadPolicy(policy) dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java) // 改用ViewBinding直接获取ListView,避免重复inflate布局 listVieww = binding.listVieww adapter = CustomListAdapter(requireContext(), listReturned) listVieww.adapter = adapter handler.postDelayed(this, 1000) return root }
额外优化建议
- 移除不必要的
inflater.inflate(R.layout.dashboard, container, false)调用,避免生成重复布局实例造成资源浪费 - 全程使用ViewBinding操作控件,替代
findViewById,降低控件匹配错误的概率 - 注意
StrictMode的使用场景,生产环境不建议直接permitAll(),避免忽略潜在的线程安全问题
内容的提问来源于stack exchange,提问作者Krzychu1289
相关产品推荐
相关产品推荐

