且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

android ListView mListView.getChildAt(i) 为null,如何解决?

更新时间:2023-11-30 22:24:34

AdapterView.getCount() 返回数据项的数量,该数量可能大于可见视图的数量,这就是您收到空指针异常的原因,因为您正在尝试查找没有的视图存在于当前可见的 ListView 项中.

AdapterView.getCount() returns the number of data items, which may be larger than the number of visible views, that's why you are getting null pointer exception, because you are trying to find views which do not exist in the current visible ListView items.

要解决此问题,您首先需要使用 getFirstVisiblePosition() 找到 ListView 中的第一个可见项,并使用 getLastVisiblePosition() 找到最后一个可见项.将 for 循环条件更改为:

To solve this issue you will first need to find the first visible item in the ListView using getFirstVisiblePosition() and the last visible item using getLastVisiblePosition(). Change the for loop condition as:

int num_of_visible_view=mListView.getLastVisiblePosition() - 
                                   mListView.getFirstVisiblePosition();

for (int i = 0; i < num_of_visible_view; i++) {
      // do your code here
 }