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

Android Kotlin项目中ListView未调用自定义Adapter的getView()问题

Android Kotlin:ListView自定义Adapter的getView()未调用问题排查与解决

问题现象

  • ListView绑定自定义ListAdapter后,日志显示getCount()返回正确的非0数值,但getView()、getItem()等方法完全未被触发
  • 尝试通过post方式设置Adapter,问题仍未解决

问题根源

在DashboardFragment的onCreateView()方法中存在布局实例不匹配的核心错误:

  1. 先通过DashboardBinding.inflate()生成了布局实例root
  2. 又通过inflater.inflate(R.layout.dashboard, container, false)生成了另一个独立的布局实例view,并在该实例中找到ListView完成Adapter绑定
  3. 最终返回的是未绑定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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:37:06