【发布时间】:2017-02-17 17:38:39
【问题描述】:
我有一个带有复选框的自定义列表视图。在主布局中有“全选”复选框。如果我选择“全选”复选框,那么所有复选框都会被选中。我想要的是当我取消选择任何一个列表视图复选框时,“全选”复选框也必须被取消选中。我尝试了here,但它不起作用。如果我取消选择任何列表视图复选框,则所有列表视图复选框都会被取消选中。
public class ContactsListAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Contacts> objects;
CheckBox _selectall;
ContactsListAdapter(Context context, ArrayList<Contacts> products, CheckBox selectall) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_selectall=selectall;
}
@Override
public int getCount() {
return objects.size();
}
@Override
public Object getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.contact_item, parent, false);
}
//final Contacts p = getProduct(position);
Contacts contacts = objects.get(position);
((TextView) view.findViewById(R.id.tvName)).setText(contacts.getName());
((TextView) view.findViewById(R.id.tvMobile)).setText(contacts.getMobile());
((TextView) view.findViewById(R.id.tvEmail)).setText(contacts.getEmail());
final CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setTag(position);
cbBuy.setChecked(contacts.box);
if(_selectall.isChecked()){
_selectall.setChecked(true);
}else{
_selectall.setChecked(false);
}
cbBuy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
if(_selectall.isChecked()){
_selectall.setChecked(true);
}else{
_selectall.setChecked(false);
}
notifyDataSetChanged();
}
});
_selectall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(_selectall.isChecked()){
for(int i=0; i<objects.size();i++){
getProduct(i).box = true;
cbBuy.setTag(i);
cbBuy.setChecked(objects.get(i).box);
}
}else{
for(int i=0; i<objects.size();i++){
getProduct(i).box = false;
cbBuy.setTag(i);
cbBuy.setChecked(objects.get(i).box);
}
}
notifyDataSetChanged();
}
});
return view;
}
Contacts getProduct(int position) {
return ((Contacts) getItem(position));
}
ArrayList<Contacts> getBox() {
ArrayList<Contacts> box = new ArrayList<Contacts>();
for (Contacts p : objects) {
if (p.box)
box.add(p);
}
return box;
}
}
【问题讨论】:
标签: android listview android-checkbox