ListView中的getChildAt(int)的注意事项
来源:互联网 发布:怎么样提升淘宝流量 编辑:程序博客网 时间:2024/05/16 18:43
在实际开发中,我们可能需要单独修改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]; }
我们发现这个传入参数是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是否被移出屏幕。
声明
原创文章,欢迎转载,请保留出处。有任何错误、疑问或者建议,欢迎指出。我的邮箱:Maxwell_nc@163.com
参考文章
http://ahua186186.iteye.com/blog/1830180
- ListView中的getChildAt(int)的注意事项
- ListView中的getChildAt的注意事项
- 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中的item控件(mListView.getChildAt(int pos))
- Android——ListView中getChildAt(index)的使用注意事项
- listview的getChildAt方法
- 关于Listview的getChildAt方法
- 8.5.4 Optimizing InnoDB Redo Logging 优化InnoDB Redo Logging
- 《第一行代码》第二章/Toast,Menu,Intent
- 结构体
- 在服务器上用Fiddler抓取HTTPS流量
- Inflate
- ListView中的getChildAt(int)的注意事项
- SQlList数据库基础
- Beginning Auto Layout Tutorial in iOS 7: Part 2
- Hadoop读写文件时内部工作机制是怎样的?
- 移动端 web
- 单个工程中Spring+Mybatis连接多个数据库的配置(个人分享版本)
- 六大安神汤
- Hadoop Streaming使用简介
- ubuntu12.04 gedit出错:Failed to connect to the session manager