ListView中的getChildAt的注意事项

在实际开发中,我们可能需要单独修改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)的注意事项:

  1. getChildCount和getCount获取的值不一定相同,在item数量少于屏幕最大显示数量时,它们两者的值相等。
  2. getChildAt传入的参数范围是0到getChildCount,超出容易出现空指针问题。
  3. 要获得当前点击的item的view对象,可以用getChildAt(position - listView.getFirstVisiblePosition())获取,注意判断修改view时,item是否被移出屏幕。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值