这是我的情况。
我所拥有的:在右上角和自定义元素列表下方带有复选框(称为“checkAll”)的活动:TextView 和复选框。
我想要什么:当点击checkAll时,列表中每个项目的所有复选框都被选中。
问题:只有当列表的所有项目都在屏幕上可见时,一切才能正常工作。当我有一个包含很多元素的列表(例如 20 个)时,然后单击 checkAll 我的应用程序崩溃。LogCat 说我:NullPointerException 就行了
CheckBox checkBoxInTheItemList = (CheckBox)
mList.getChildAt(i).findViewById(R.id.checkBox);
这是我的功能:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout_select_friend);
checkAll =(CheckBox)findViewById(R.id.checkBoxAll);
checkAll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if((checkAll.isChecked())){
for(int i=1;i<peopleSize;i++){//for each element of my array of Person
mList=(ListView) findViewById(R.id.list); //This is the id of my List
//in the list_layout_select_friend
CheckBox checkBoxInTheItemList = (CheckBox)
mList.getChildAt(i).findViewById(R.id.checkBox); //i try to get
//for each item of the List the relative checkBox.
checkBoxInTheItemList.setChecked(true);//Now i checked the checkBox
}
}
}
});
}
编辑:这是我的适配器,还有 getView 方法
public class NewQAAdapterSelectFriends extends BaseAdapter {
private LayoutInflater mInflater;
private Person[] data;
public NewQAAdapterSelectFriends(Context context) {
mInflater = LayoutInflater.from(context);
}
public void setData(Person[] data) {
this.data = data;
}
@Override
public int getCount() {
return data.length;
}
@Override
public Object getItem(int item) {
return data[item];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_select_friends, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);
convertView.setTag(viewHolder);
viewHolder.nameText.setTag(viewHolder.nameText);
viewHolder.nameText.setTag(viewHolder.surnameText);
viewHolder.contactImage.setTag(data[position]);
viewHolder.checkBox.setTag(data[position]);// is correct this line??????
} else {
}
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.nameText.setText(data[position].getName());
holder.surnameText.setText(data[position].getSurname());
holder.contactImage.setImageResource(data[position].getPhotoRes());
holder.contactImage.setScaleType(ScaleType.FIT_XY);
//here i have to write something for the checkbox, right?
return convertView;
}
static class ViewHolder {
TextView nameText;
TextView surnameText;
ImageView contactImage;
CheckBox checkBox;
}
我怎样才能避免这个问题?我如何检查带有不可见元素的大列表的所有复选框?