在实际开发中,我们可能需要单独修改ListView中的某一个view的内容,如果使用适配器上的notifyDataSetChanged()方法的话会显得有些多余,而且会导致用户体验差,这时候可以使用getChildAt(int)方法单独获取某个view进行修改。
但是注意,这个方法如果使用不当的话很容易出现空指针异常。
首先先来看看方法的注释说明:
View android.view.ViewGroup.getChildAt(int index)
Returns the view at the specified position in the group.
Parameters: index the position at which to get the view from
Returns: the view at the specified position or null if the position
does not exist within the group
乍一看好像没有什么坑,我们再跳到源码看看:
/**
* Returns the number of children in the group.
*
* @return a positive integer representing the number of children in
* the group
*/
public int getChildCount() {
return mChildrenCount;
}
/**
* Returns the view at the specified position in the group.
*
* @param index the position at which to get the view from
* @return the view at the specified position or null if the position
* does not exist within the group
*/
public View getChildAt(int index) {
if (index < 0 || index >= mChildrenCount) {
return null;
}
return mChildren[index];
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
我们发现这个传入参数是0到getChildCount,而不是0到getCount,那么这两个Count有什么区别呢?
首先getChildCount是当前屏幕显示了的view数量,因为ListView的Adapter用传入convertView,这样就可以理解为什么getChildAt(int)会出现空指针异常了。
首先getChildAt(int)只能获取当前屏幕中显示的item的view对象,因为其他不在显示的view对象并不存在于内存中,如果用户复用了convertView,那么mChildren这个view[]集合里面的对象不变,但已经对应不同的item了。
使用getChildAt(int)方法一定要注意判断获取的item是否在屏幕中显示,即
取值范围在 >= listView.getFirstVisiblePosition() && <= listView.getLastVisiblePosition();
总结
使用getChildAt(int)的注意事项:
- getChildCount和getCount获取的值不一定相同,在item数量少于屏幕最大显示数量时,它们两者的值相等。
- getChildAt传入的参数范围是0到getChildCount,超出容易出现空指针问题。
- 要获得当前点击的item的view对象,可以用
getChildAt(position - listView.getFirstVisiblePosition())
获取,注意判断修改view时,item是否被移出屏幕。