手把手教你实现GridView中Checkbox全选

全选效果图

这节讲得相对比较基础的东西,高手请忽略。

首先新建一个GridviewAdapter继承BaseAdapter

public class GridviewAdapter extends BaseAdapter{  
    private ArrayList<Person> list;  
    private static HashMap<Integer,Boolean> isSelected;  
    private Context context;  
    private LayoutInflater inflater = null;  
    public GridviewAdapter(ArrayList<Person> list, Context context) {  
        this.context = context;  
        this.list = list;  
        inflater = LayoutInflater.from(context);  
        isSelected = new HashMap<Integer, Boolean>();  
        initDate();  
    }  
    private void initDate(){  
        for(int i=0; i<list.size();i++) {  
            getIsSelected().put(i,false);  
        }  
    }  
    @Override  
    public int getCount() {  
        return list.size();  
    }  
    @Override  
    public Object getItem(int position) {  
        return list.get(position);  
    }  
    @Override  
    public long getItemId(int position) {  
        return position;  
    }  
    @Override  
    public View getView(final int position, View convertView, ViewGroup parent) {  
        ViewHolder holder = null;  
            if (convertView == null) {  
            holder = new ViewHolder();  
            convertView = inflater.inflate(R.layout.gridviewitem, null);  
            holder.name = (TextView) convertView.findViewById(R.id.item_name);  
            holder.ID = (TextView) convertView.findViewById(R.id.item_ID);  
            holder.cb = (CheckBox) convertView.findViewById(R.id.item_cb);  
            convertView.setTag(holder);  
        } else {  
            holder = (ViewHolder) convertView.getTag();  
            }  
        holder.ID.setText(list.get(position).getId());  
        holder.name.setText(list.get(position).getName());  
        holder.cb.setChecked(getIsSelected().get(position));  
        return convertView;  
    }  
    static class ViewHolder{    
        CheckBox cb;    
        TextView name;    
        TextView ID;    
    }  
    public static HashMap<Integer,Boolean> getIsSelected() {  
        return isSelected;  
    }  
    public static void setIsSelected(HashMap<Integer,Boolean> isSelected) {  
        GridviewAdapter.isSelected = isSelected;  
    }  
  
}  

需要留意的是 用来保存选择状态

public static HashMap<Integer,Boolean> getIsSelected() {  
        return isSelected;  
    }  
public static void setIsSelected(HashMap<Integer,Boolean> isSelected) {  
        GridviewAdapter.isSelected = isSelected;  
    }  

下面我们新建一个Activity来看看效果:

public class MainActivity extends Activity implements OnClickListener {  
    private GridView gd;  
    private GridviewAdapter mAdapter;  
    private ArrayList<Person> persons;  
    private Button bt_selectall;  
    private Button bt_cancel;  
    private Button bt_deselectall;  
    private Button bt_sumit;  
    private int checkNum; // 记录选中的条目数量  
    private TextView tv_show;// 用于显示选中的条目数量  
    List<String> selectID = new ArrayList<String>(); //选中的ID  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        initView();  
        initData();  
        gd.setOnItemClickListener(new OnItemClickListener() {  
            @Override  
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
                    long arg3) {  
                ViewHolder holder = (ViewHolder) arg1.getTag();  
                holder.cb.toggle();  
                GridviewAdapter.getIsSelected().put(arg2, holder.cb.isChecked());  
                if (holder.cb.isChecked() == true) {  
                    checkNum++;  
                } else {  
                    checkNum--;  
                }  
                tv_show.setText("已选中" + checkNum + "项");  
            }  
        });  
    }  
    /** 
     * 初始化数据 
     */  
    private void initData() {  
        Person mPerson;  
        for (int i = 1; i <= 40; i++) {  
            mPerson = new Person();  
            mPerson.setName("aikaifa" + i);  
            // mPerson.setId(Character.valueOf((char)(i+65))+" ");  
            mPerson.setId(i + "");  
            persons.add(mPerson);  
        }  
        mAdapter = new GridviewAdapter(persons, this);  
        gd.setAdapter(mAdapter);  
    }  
  
    /** 
     * 刷新 
     */  
    private void dataChanged() {  
        mAdapter.notifyDataSetChanged();  
        tv_show.setText("已选中" + checkNum + "项");  
    }  
  
    /** 
     * 初始化控件 
     */  
    private void initView() {  
        gd = (GridView) findViewById(R.id.gd);  
        bt_selectall = (Button) findViewById(R.id.bt_selectall);  
        bt_cancel = (Button) findViewById(R.id.bt_cancelselectall);  
        bt_deselectall = (Button) findViewById(R.id.bt_deselectall);  
        bt_sumit = (Button) findViewById(R.id.bt_submit);  
        tv_show = (TextView) findViewById(R.id.tv);  
        persons = new ArrayList<Person>();  
          
        bt_selectall.setOnClickListener(this);  
        bt_cancel.setOnClickListener(this);  
        bt_deselectall.setOnClickListener(this);  
        bt_sumit.setOnClickListener(this);  
    }  
  
    /** 
     * 全选 
     */  
    private void selectAll() {  
        for (int i = 0; i < persons.size(); i++) {  
            GridviewAdapter.getIsSelected().put(i, true);  
        }  
        // 数量设为list的长度  
        checkNum = persons.size();  
        dataChanged();  
    }  
  
    /** 
     * 全不选 
     */  
    private void cancelselectall() {  
        // 遍历list的长度,将已选的按钮设为未选  
        for (int i = 0; i < persons.size(); i++) {  
            if (GridviewAdapter.getIsSelected().get(i)) {  
                GridviewAdapter.getIsSelected().put(i, false);  
                checkNum--;// 数量减1  
            }  
        }  
        dataChanged();  
    }  
  
    /** 
     * 反选 
     */  
    private void deselectall() {  
        // 遍历list的长度,将已选的设为未选,未选的设为已选  
        for (int i = 0; i < persons.size(); i++) {  
            if (GridviewAdapter.getIsSelected().get(i)) {  
                GridviewAdapter.getIsSelected().put(i, false);  
                checkNum--;  
            } else {  
                GridviewAdapter.getIsSelected().put(i, true);  
                checkNum++;  
            }  
        }  
        dataChanged();  
    }  
  
    /** 
     * 提交 
     */  
    private void submit() {  
        selectID.clear();  
        for (int i = 0; i < mAdapter.getIsSelected().size(); i++) {  
            if (mAdapter.getIsSelected().get(i)) {  
                selectID.add(persons.get(i).getId());  
            }  
        }  
  
        if (selectID.size() == 0) {  
            AlertDialog.Builder builder1 = new AlertDialog.Builder(  
                    MainActivity.this);  
            builder1.setMessage("没有选中任何记录");  
            builder1.show();  
        } else {  
            StringBuilder sb = new StringBuilder();  
  
            for (int i = 0; i < selectID.size(); i++) {  
  
                sb.append("ID=" + selectID.get(i) + "  ");  
  
            }  
            AlertDialog.Builder builder2 = new AlertDialog.Builder(MainActivity.this);  
            builder2.setMessage(sb.toString());  
            builder2.show();  
        }  
    }  
  
    @Override  
    public void onClick(View v) {  
        switch (v.getId()) {  
        case R.id.bt_selectall:  
            selectAll();  
            break;  
        case R.id.bt_cancelselectall:  
            cancelselectall();  
            break;  
        case R.id.bt_deselectall:  
            deselectall();  
            break;  
        case R.id.bt_submit:  
            submit();  
            break;  
        }  
    }  
}  

对应的activity_main.xml布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:id="@+id/LinearLayout1"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical"  
>  
 <LinearLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:orientation="horizontal"  
        >  
  
        <Button  
            android:id="@+id/bt_selectall"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="全选" />  
  
        <Button  
            android:id="@+id/bt_cancelselectall"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="全不选" />  
  
        <Button  
            android:id="@+id/bt_deselectall"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="反选" />  
  
        <Button  
            android:id="@+id/bt_submit"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="提交" />  
  
    </LinearLayout>  
  
    <TextView  
        android:id="@+id/tv"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="TextView" />  
  
    <GridView  
        android:id="@+id/gd"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        android:numColumns="2" />  
</LinearLayout>  

其中有个实体类

public class Person {  
    private String name;  
    private String Id;  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public String getId() {  
        return Id;  
    }  
    public void setId(String id) {  
        Id = id;  
    }     
}  

gridviewitem.xml布局

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:orientation="horizontal" >  
    <TextView  
        android:id="@+id/item_ID"  
        android:layout_width="0dp"  
        android:layout_height="wrap_content"  
        android:layout_weight="1"  
        android:gravity="center_vertical"  
        android:visibility="gone" />  
    <TextView  
        android:id="@+id/item_name"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:gravity="center_vertical" />  
    <CheckBox  
        android:id="@+id/item_cb"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:clickable="false"  
        android:focusable="false"  
        android:focusableInTouchMode="false"  
        android:gravity="center_vertical" />  
</LinearLayout>  

这样,关于GridView中Checkbox全选的功能就算完成了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,570评论 25 707
  • 1.什么是Activity?问的不太多,说点有深度的 四大组件之一,一般的,一个用户交互界面对应一个activit...
    JoonyLee阅读 5,670评论 2 51
  • 前几天整理了Java面试题集合,今天再来整理下Android相关的面试题集合.如果你希望能得到最新的消息,可以关注...
    Boyko阅读 3,581评论 8 135
  • http://blog.csdn.net/u012763794/article/details/51207833 ...
    查无此人asdasd阅读 347评论 0 0
  • hey,我来了。 以前一直在豆瓣,写了很多,直到有一天回望才发现过去的自己依然有无法面对的地方。当过去彻底成为过去...
    西西粒呀阅读 108评论 0 0