Android的ListView的mListView.getChildAt(i)为空,怎么解决呢?为空、ListView、Android、getChildAt

2023-09-12 10:21:19 作者:╰゛粨毐不侵 つ

我创建低于code:

 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);
                }
            }

        }
    });

我想实现像当我点击列表视图中的一项功能,它会显示一个视图,列表视图的其他项目将被隐藏。但 mListView.getChildAt(我)将有空指针超过后 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.

要解决这个问题,首先需要使用发现,在ListView中第一个可见项目 getFirstVisiblePosition()和使用的最后一个可见项目 getLastVisiblePosition ()。更改为循环条件为:

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
 }