MainActivity.class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findComp();
initData();
adapter = new Myadapter(this, list);
lv.setAdapter(adapter);
//全选
all.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i=0;i<list.size();i++){
list.get(i).setIsstate(true);
}
adapter.notifyDataSetChanged();
}
});
//删除,选择的按钮列表
del.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//遍历集合,如果是选中,则把它删除
for(int i=0;i<list.size();i++){
if(list.get(i).isIsstate()){
//删除集合中的数据
list.remove(i);
/*
*由于删除集合中的数据后,数据会在列表中上移一位,那么集合中的position,
*和列表中的条目ID不再匹配,所以要减1
*/
i=i-1;
}
}
adapter.notifyDataSetChanged();
}
});
//反选
fan.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i=0;i<list.size();i++){
//得到集合中的复选框的按钮
boolean isstate=list.get(i).isIsstate();
//把集合中的复选框的状况,取非,把当前状态改变
list.get(i).setIsstate(!isstate);
}
//刷新,列表
adapter.notifyDataSetChanged();
}
});
}
//添加集合
private void initData() {
list = new ArrayList<Info>();
list.add(new Info("李彬"));
list.add(new Info("李彬初号机"));
list.add(new Info("李彬三待机"));
list.add(new Info("李彬四代机"));
}
Myadapter.class
public class Myadapter extends BaseAdapter {
public Context context;
public ArrayList<Info> list;
private ViewHodler vh;
public Myadapter(Context context, ArrayList<Info> list) {
super();
this.context = context;
this.list = list;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int arg0, View contrain, ViewGroup arg2) {
// TODO Auto-generated method stub
//优化
if(contrain==null){
contrain=View.inflate(context, R.layout.item, null);
vh = new ViewHodler();
vh.title=(TextView) contrain.findViewById(R.id.t_title);
vh.ck=(CheckBox) contrain.findViewById(R.id.c_ck);
contrain.setTag(vh);
}else{
vh=(ViewHodler) contrain.getTag();
}
vh.title.setText(list.get(arg0).getTitle());
vh.ck.setChecked(list.get(arg0).isIsstate());
//当条目改变状态后,把改变后的状态,存入集合中
vh.ck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
list.get(arg0).setIsstate(isChecked);
}
});
return contrain;
}
public class ViewHodler{
private TextView title;
private CheckBox ck;
}
}