Android带CheckBox的ListView,全选,CheckBox和ListView事件分离

当ListView有CheckBox的时候,容易出现各种问题。

常见问题:

无法点击列表原因:CheckBox占用焦点,设置它的android:focusable为false即可。

当前页某个选框被选中,下拉列表后,新列表的同样位置也被选中:不要根据viewHolder.checkBox的isChecked()判断,改为用那个hashmap的状态判断。

下拉列表再拉回来后状态丢失:同上,hashmap存储解决问题。
Android带CheckBox的ListView,全选,CheckBox和ListView事件分离_第1张图片

以下代码参考了http://blog.csdn.net/onlyonecoder/article/details/8687811博客,不过他的是把CheckBox的clickable属性禁掉了,实现点任一条列表(包括点文字和点选框)都改变CheckBox的状态,然而有时候我们需要点列表的文字时触发文字效果且不影响选中状态。


将ListView里的CheckBox点击放在适配器里,其他放MainActivity里。



MainActivity.java 主类

package com.example.xiaoguang.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private List itemBeansList;
    public static int selectNum = 0;
    public static TextView text_num;
    private MyAdapter mAdapter;
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectNum = 0;
        text_num = (TextView)findViewById(R.id.textview_num);
        itemBeansList = new ArrayList<>();

        itemBeansList.add(new ItemBean(R.mipmap.ic_launcher,"点listview(text和img)不影响checkbox","yes"));
        for(int i = 1; i <= 30; i++){
            itemBeansList.add(new ItemBean(R.mipmap.ic_launcher,"Text"+i,"yes"));
        }

        mAdapter = new MyAdapter(MainActivity.this,itemBeansList);
        listView = (ListView)findViewById(R.id.mainListView);
        listView.setAdapter(mAdapter);

        Button btn_sellectAll =(Button)findViewById(R.id.btn_selectAll);
        Button btn_sellectBack =(Button)findViewById(R.id.btn_selectBack);
        Button btn_sellectNone =(Button)findViewById(R.id.btn_selectNone);
        btn_sellectAll.setOnClickListener(this);
        btn_sellectBack.setOnClickListener(this);
        btn_sellectNone.setOnClickListener(this);
        //点文字层
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                MyAdapter.ViewHolder holder = (MyAdapter.ViewHolder)view.getTag();//避免了findViewById
                holder.textView.setText("被点过");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_selectAll:
                for(int i = 0; i < itemBeansList.size(); i++){
                    MyAdapter.getMapSelected().put(i,true);
                }
                selectNum = itemBeansList.size();
                break;
            case R.id.btn_selectBack:
                selectNum = 0;
                for(int i = 0; i < itemBeansList.size(); i++){
                    boolean selectState = MyAdapter.getMapSelected().get(i);
                    if(selectState == false){
                        selectNum ++;
                    }
                    MyAdapter.getMapSelected().put(i,!selectState);
                }
                break;
            case R.id.btn_selectNone:
                for(int i = 0; i < itemBeansList.size(); i++){
                    MyAdapter.getMapSelected().put(i,false);
                }
                selectNum = 0;
                break;
        }
        dataChanged();
    }
    private void dataChanged(){     //更新UI
        mAdapter.notifyDataSetChanged();
        text_num.setText("选中" + selectNum + "项");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

MyAdapter.java 适配器

package com.example.xiaoguang.myapplication;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;

/**
 * Created by xiaoguang on 2015/8/22.
 */
public class MyAdapter extends BaseAdapter{
    private Context mcontext;
    private ViewHolder viewHolder;
    private List mlist;
    private LayoutInflater mInflater;
    private static HashMap mapIsSelected;
    public MyAdapter(Context context,List list){
        mcontext = context;
        mlist = list;
        mInflater = LayoutInflater.from(context);
        mapIsSelected = new HashMap<>();
        initMapIsSelected();
    }
    private void initMapIsSelected(){
        for (int i = 0; i < mlist.size(); i++) {
            mapIsSelected.put(i, false);
        }
    }
    public int getCount() {
        return mlist.size();
    }

    @Override
    public Object getItem(int position) {
        return mlist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if(convertView == null){
            viewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item,null);
            viewHolder.imageView = (ImageView)convertView.findViewById(R.id.imageview);
            viewHolder.textView = (TextView)convertView.findViewById(R.id.textview);
            viewHolder.checkBox = (CheckBox)convertView.findViewById(R.id.checkbox);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder)convertView.getTag();
        }
        ItemBean bean = mlist.get(position);
        viewHolder.imageView.setImageResource(bean.ItemPicId);
        viewHolder.textView.setText(bean.ItemTextView);
        viewHolder.checkBox.setText(bean.ItemCheckBox);
        viewHolder.checkBox.isChecked()
        //根据选择的状态设定checkBox显示状态
        viewHolder.checkBox.setChecked(getMapSelected().get(position)); //没有这句就会出现隔页的同位置同状态
        viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("ddd",position+"");
//                Log.e("eee", "点击了" + position + ",原状态是" + getMapSelected().get(position));
                getMapSelected().put(position,  !getMapSelected().get(position));//不能根据checkbox状态
                if( getMapSelected().get(position) ){
                    MainActivity.selectNum ++;
                }else{
                    MainActivity.selectNum --;
                }
                viewHolder.checkBox.setChecked(getMapSelected().get(position));
                MainActivity.text_num.setText("选中" + MainActivity.selectNum + "项");
            }
        });
        return convertView;
    }
    public static HashMap getMapSelected(){
        return mapIsSelected;
    }

    public static class ViewHolder{
        TextView textView;
        CheckBox checkBox;
        ImageView imageView;
    }
}


ItemBean.java 放数据的

package com.example.xiaoguang.myapplication;

/**
 * Created by xiaoguang on 2015/8/23.
 */
public class ItemBean {
    public String ItemTextView;
    public int ItemPicId;
    public String ItemCheckBox;
    public ItemBean(int ItemPicId,String ItemTextView,String ItemCheckBox){
        this.ItemPicId = ItemPicId;
        this.ItemTextView = ItemTextView;
        this.ItemCheckBox = ItemCheckBox;
    }
}


上布局文件


activity_main.xml 主布局文件


    
    
        

Item.xml 每个小列表的内容



	
    

	




工程是Android Studio工程,为了方便直接把Gradle配置也打包了,0分下载地址 点这里。






你可能感兴趣的:(Android带CheckBox的ListView,全选,CheckBox和ListView事件分离)