android ListView mListView.getChildAt(i) 为null,如何解决? [英] android ListView mListView.getChildAt(i) is null, how to solve it?

查看:24
本文介绍了android ListView mListView.getChildAt(i) 为null,如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下代码:

 mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position,
                long id) {

            for (int i = 0; i < mListView.getCount(); i++) {
                View callLogView = mListView.getChildAt(i);   
                mRelativeLayout = (LinearLayout)callLogView.findViewById(R.id.myShow);
                if(i == position){
                    if(mRelativeLayout.getVisibility() == View.GONE){
                        mRelativeLayout.setVisibility(View.VISIBLE);
                    }
                    else{
                        mRelativeLayout.setVisibility(View.GONE);
                    }
                }else{
                    mRelativeLayout.setVisibility(View.GONE);
                }
            }

        }
    });

我想实现一个功能,比如当我点击Listview的一项时,它会显示一个视图,而Listview的其他项将被隐藏.但是mListView.getChildAt(i)超过mListView.getChildCount()后会有空指针.

I want to realize a function like when i click one item of Listview, it will show a view, and the other items of Listview will be hidden. But mListView.getChildAt(i) will have the null pointer after exceed mListView.getChildCount().

如何解决这个问题?提前致谢!

How to solve this? Thanks in advance!

推荐答案

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
 }

这篇关于android ListView mListView.getChildAt(i) 为null,如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆