android中的listview计数与适配器计数

Posted

技术标签:

【中文标题】android中的listview计数与适配器计数【英文标题】:listview count vs adapter count in android 【发布时间】:2013-10-09 04:15:47 【问题描述】:

为什么listview.getChildCount()adapter.getCount() 返回不同的值?我有一个 onScroll 方法,如果我调用上面的方法,每个方法都会返回不同的值。有谁知道为什么?

【问题讨论】:

参考this 【参考方案1】:

ListView.getChildCount() 返回屏幕上Views 的数量。 Adapters getCount() 返回列表中的对象总数。

getChildCount()

getCount()

你可能有 50 个Strings 说一个ArrayAdapter,但目前只有 10 个被绘制在屏幕上,所以你的 ListView 计数将是 10,但你的 Adapter 计数将是 50。

【讨论】:

如果我这样做 listview.getChildAt(index) 必须 index[0,listView.getChildCount() ) 或者索引可以是 [0,adapter.getCount() ) 之间的任何东西? [0,listView.getChildCount() )。否则,您可能会得到IndexOutOfBoundsException,因为就像我的示例所示,您的List 中的项目可能比ListView 中的当前项目多 现在,您可以采用其他方式,但您需要包裹在 try/catch 中才能捕获 IOB Exception【参考方案2】:

adapter.getCount() 返回其中包含的对象总数。 listView.getChildCount() 返回此列表视图中显示的视图数。 Adapter使用了缓存机制,很多view都被复用了,所以和adapter.getCount()显示的不一样

【讨论】:

感谢发帖。 +1

以上是关于android中的listview计数与适配器计数的主要内容,如果未能解决你的问题,请参考以下文章

android - listview 过滤器计数

Android RecyclerView 适配器项目计数在单元测试中返回 0

ArrayIndexOutOfBoundsException 与 ListView 中的多个视图的自定义 Android 适配器

Android--ListView与数据绑定(Xamarin)

Android listview 的用法? 越详细越好。

Android 如何在阅读列表项计数时停止包含页脚行的 TalkBack