Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android ListView mListView.getChildAt(i) is null, how to solve it?

I create the below 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);
                }
            }

        }
    });

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!

like image 622
DaringLi Avatar asked Jan 31 '13 05:01

DaringLi


2 Answers

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.

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
 }
like image 187
ρяσѕρєя K Avatar answered Oct 11 '22 08:10

ρяσѕρєя K


you can not implement this in onItemClick.

As you can access only visible child not all child.

What you can do is on onItemClick

you can send the position in adapter

and then set the logic there in getView too change view

and update the adapter in listview, or notify for changes.

like image 21
Nimish Choudhary Avatar answered Oct 11 '22 09:10

Nimish Choudhary