In order to implement this, you'll need an understanding of how ListView work, namely view recycling. When a list is made in Android, the Views are created dynamically. As you scroll up and down, list items that go off the screen need to have their views wiped clean of data and be repopulated with information for the next item coming in. This happens in the getView
method in your List Adapter (which, by the way, would be very helpful for you to post). I believe this is your reason for the Null Pointer Exception. The getChildAt
method can only return visible list items, because the others do not exist at the moment. The first visible item will be index 0. So even though your list may have 20 items, if only 5 are visible, only 5 can be returned by getChildAt, and asking for a view that's out of bounds could cause this exception.
The way I would approach your item is by having a data structure that keeps a record of your list items and the state of the check box. A very simple example of this would be an array of booleans, where the true/false value corresponds to if the box is checked. When getView()
is called, you can use the position
argument a your as the index to your array, and check or uncheck the box based on this. (You probably should be doing something like this anyway, if you're recycling your views properly) If the Check All button is pressed, then just make each element of the array true.
Some sample code to help you out.
private boolean[] isCheckedArray; //Maintains the checked state of your
... //At some point, probably onCreate or whenever you get your data, initialize your array. If nothing every starts checked off, initialize the whole array to false
checkAll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0){
for(int i=1;i<peopleSize;i++)
isCheckedArray[i] = true;
}
});
...
//And finally, in your getView function
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
...
myCheckBox.setChecked(isCheckedArray[position])
...
}
Hope this helps. I'd definitely look into view recycling in Android, as it's a key concept and having a good handle on it will save you a lot of time and headache down the road. Good luck.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…