首先说明每个Item的资源和选中状态全部保存到javaBean对象中;
创建要给javaBean即可保存每个item的状态;
当点击某个item的时候获取对应的javaBean对象改变里面的参数,然后刷新adapter;
点击全选的时候把集合里面所有的javaBean对象里面保存选中状态的参数设置为选中状态,然后刷新adapter;
同理,当选中反选的时候设置参数为反,然后刷新adapter;
当选中全不选的时候把对应参数全部设置为没有选中状态,然后刷新adapter;
布局的话就非常简单了,整体是一个纵向的线性布局,里面是一个ListView,下面是一个横向的线性布局,在这里我就不在粘贴布局的代码了;
然后我们看下activity的代码:
public class MainActivity extends Activity implements View.OnClickListener {
Context context;
private ListView mListView;
//存放HeroBean的集合
private List<HeroBean> heroBeanList;
//全选,反选,全不选
private TextView tvSelectAll;
private TextView tvSelectOther;
private TextView tvSelectNull;
String[] names={"吕布","赵云","典韦","关羽","马超","张飞","黄忠","许褚","孙策","孙坚"
,"夏侯敦","夏侯渊","文丑","颜良","张合","张辽","徐晃","甘宁","华雄","姜维","曹仁"
,"李典","黄盖","周喻","夏侯霸","公孙瓒","曹操","刘备","陆逊" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
initDate();
initView();
}
//初始化数据
private void initDate() {
heroBeanList=new ArrayList<>();
for(int x=0;x<names.length;x++){
HeroBean heroBean=new HeroBean();
heroBean.name=names[x];
heroBeanList.add(heroBean);
}
}
MyListViewAdapter adapter;
private void initView() {
//全选,反选,全不选
tvSelectAll= (TextView) findViewById(R.id.tv_select_all);
tvSelectOther= (TextView) findViewById(R.id.tv_select_other);
tvSelectNull= (TextView) findViewById(R.id.tv_select_null);
mListView= (ListView) findViewById(R.id.listview);
adapter = new MyListViewAdapter(context, heroBeanList);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//当点击某个item是切换是否选中状态
heroBeanList.get(position).select=!heroBeanList.get(position).select;
//刷新adapter
adapter.notifyDataSetChanged();
ToastUtils.showToast(context,heroBeanList.get(position).name);
}
});
//给 全选,反选,全不选 设置点击事件
tvSelectAll.setOnClickListener(this);
tvSelectNull.setOnClickListener(this);
tvSelectOther.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_select_all://全选
for(int x=0;x<heroBeanList.size();x++){
heroBeanList.get(x).select=true;
adapter.notifyDataSetChanged();
}
break;
case R.id.tv_select_other://反选
for(int x=0;x<heroBeanList.size();x++){
heroBeanList.get(x).select= !heroBeanList.get(x).select;
adapter.notifyDataSetChanged();
}
break;
case R.id.tv_select_null://全不选
for(int x=0;x<heroBeanList.size();x++){
heroBeanList.get(x).select=false;
adapter.notifyDataSetChanged();
}
break;
}
}
}
需要注意的是在adapter中设置ImageView的时候使用if的话必须写else;