ListView中的getChildAt的注意事项
来源:互联网 发布:c语言编译器手机版 编辑:程序博客网 时间:2024/05/29 09:14
在实际开发中,我们可能需要单独修改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是否被移出屏幕。
- ListView中的getChildAt的注意事项
- ListView中的getChildAt(int)的注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- ListView中getChildAt(index)的使用注意事项
- Android——ListView中getChildAt(index)的使用注意事项
- listview的getChildAt方法
- 关于Listview的getChildAt方法
- 关于ListView的getChildAt(index)
- 美国人开发了一个有趣的网站,可以算出你被机器人抢饭碗的概率
- Jamming with Ubuntu 2017——用开源技术打造物联网应用
- CXF--整合Spring
- boost asio 分析1
- 模拟实现容器List(迭代器)
- ListView中的getChildAt的注意事项
- Android --- 内存中记录位图(图片三级缓存实现)
- 这是本年度最“感性”手机——对新发布的三星 Galaxy Note 8,你是否还“敢爱” ?
- 马斯克在 Instagram 大秀 SpaceX 宇航服,满满科幻感
- Struts2 登录界面
- 万中选一,北京升哲科技荣获首个物联网行业 IDEA 金奖
- 四维图新联手铂骏科技,推出充电网络地图
- 苹果自动驾驶遭遇挫折,转而开发园区穿梭大巴
- 阿里云开放华北5,继续加注云市场投入