public class MainActivity extends Activity {
private ListView list_view;
private CheckAdapter checkAdapter;
private CheckBox allBox;
private Button reverse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_view = (ListView)findViewById(R.id.list_view);
allBox = (CheckBox)findViewById(R.id.all);
reverse = (Button)findViewById(R.id.reverse);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 15; i++) {
list.add("这是条目" + i);
}
checkAdapter = new CheckAdapter(getApplicationContext(), list);
list_view.setAdapter(checkAdapter);
//设置全选
allBox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean flag = allBox.isChecked();
for (int i = 0; i < checkAdapter.getSelect().size(); i++) {
checkAdapter.getSelect().set(i, flag);
}
//通知适配器
checkAdapter.notifyDataSetChanged();
}
});
//反选
reverse.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (! checkAdapter.getSelect().contains(true)) {
Toast.makeText(MainActivity.this, "qingxuanz", 0).show();
}else {
for (int i = 0; i < checkAdapter.getSelect().size(); i++) {
if (checkAdapter.getSelect().get(i)) {
checkAdapter.getSelect().set(i, false);
}else {
checkAdapter.getSelect().set(i, true);
}
}
if (checkAdapter.getSelect().contains(false)) {
allBox.setChecked(false);
}
checkAdapter.notifyDataSetChanged();
}
}
});
}
//适配器
private class CheckAdapter extends BaseAdapter {
private List<String> list;
private Context context;
//创建一个集合 去记录选中与未选中的状态,为了防止滑动是ck错乱
LinkedList<Boolean> linkedList = new LinkedList<Boolean>();
public CheckAdapter(Context context, List<String> list) {
// TODO Auto-generated constructor stub
this.list = list;
this.context = context;
for (int i = 0; i < list.size(); i++) {
linkedList.add(false);
}
}
//对外提供一个方法 获取这个集合
private List<Boolean> getSelect() {
return linkedList;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(context, R.layout.item, null);
}
CheckBox ck = (CheckBox) convertView.findViewById(R.id.ck);
TextView tView = (TextView) convertView.findViewById(R.id.tv);
tView.setText(list.get(position));
ck.setChecked(linkedList.get(position));
//对checkBox点击进行监听
ck.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//点中的时候改成相反的值
linkedList.set(position, !linkedList.get(position));
//点击的同时还要去判断全选
if (linkedList.contains(false)) {
allBox.setChecked(false);
}else {
allBox.setChecked(true);
}
notifyDataSetChanged();
}
});
return convertView;
}
}
}
单选,全选,反选简单Demo
最新推荐文章于 2024-07-05 15:30:51 发布