欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android基于ListView和CheckBox实现多选和全选记录的功能

程序员文章站 2024-03-01 14:29:40
应用开发中经常会有从数据库中读取数据显示,然后选中多条、全部记录并且删除的需求。在做定制系统联系人的时候也遇到这样的需求,下面写个简单的通过listview和checkbo...

应用开发中经常会有从数据库中读取数据显示,然后选中多条、全部记录并且删除的需求。在做定制系统联系人的时候也遇到这样的需求,下面写个简单的通过listview和checkbox实现多选、全选的例子。下面是具体的代码.

效果如下:

android基于ListView和CheckBox实现多选和全选记录的功能

multiselectactivity

/** 
 * multiselectactivity 
 */ 
public class multiselectactivity extends activity implements onclicklistener, 
    onitemclicklistener { 
  private static final string tag = "multiselectactivity"; 
  private listview contactsdellist; 
  private button contactsdelbtn; 
  private button contactscancelbtn; 
  private checkbox selectall; 
  private cursor cursor; 
  private contactsdeleteadapter contactsdeleteadapter; 
 
  private static final string[] projection = new string[] { contacts._id, 
      contacts.display_name }; 
  private static final int contacts_id_index = 0; 
  private static final int display_name_index = 1; 
  private contactsdeletelistitemviews holderviews; 
 
  private final class contactsdeletelistitemviews { 
    textview nameview; 
    checkbox delcheckbox; 
  } 
 
  @override 
  public void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.contacts_delete_activity); 
    contactsdellist = (listview) findviewbyid(r.id.contacts_delete_list); 
    contactsdelbtn = (button) findviewbyid(r.id.contacts_delete_btn); 
    contactscancelbtn = (button) findviewbyid(r.id.contacts_cancel_btn); 
    selectall = (checkbox) (findviewbyid(r.id.contacts_delete_list_header) 
        .findviewbyid(r.id.select_all)); 
    contactsdellist.setonitemclicklistener(this); 
    contactsdelbtn.setonclicklistener(this); 
    contactscancelbtn.setonclicklistener(this); 
    selectall.setonclicklistener(this); 
  } 
 
  @override 
  protected void onresume() { 
    super.onresume(); 
    refreshdata(); 
  } 
 
  // 查询数据库 
  private void refreshdata() { 
    cursor = getcontentresolver().query(contacts.content_uri, projection, 
        null, null, null); 
    contactsdeleteadapter = new contactsdeleteadapter(this, cursor); 
    contactsdellist.setadapter(contactsdeleteadapter); 
  } 
 
  class contactsdeleteadapter extends baseadapter { 
    cursor cur; 
    map<integer, boolean> selectedmap; 
    hashset<string> delcontactsidset; 
 
    public contactsdeleteadapter(context context, cursor c) { 
      cur = c; 
      // 保存每条记录是否被选中的状态 
      selectedmap = new hashmap<integer, boolean>(); 
      // 保存被选中记录作数据库表中的id 
      delcontactsidset = new hashset<string>(); 
 
      for (int i = 0; i < cur.getcount(); i++) { 
        selectedmap.put(i, false); 
      } 
    } 
 
    @override 
    public view getview(int position, view convertview, viewgroup parent) { 
      if (convertview == null) { 
        convertview = layoutinflater.from(multiselectactivity.this) 
            .inflate(r.layout.contacts_delete_list_item, null); 
        holderviews = new contactsdeletelistitemviews(); 
        holderviews.nameview = (textview) convertview 
            .findviewbyid(r.id.name); 
        holderviews.delcheckbox = (checkbox) convertview 
            .findviewbyid(r.id.delete_list_item); 
        convertview.settag(holderviews); 
      } 
      cur.movetoposition(position); 
      contactsdeletelistitemviews views = (contactsdeletelistitemviews) convertview 
          .gettag(); 
      final string name = cur.getstring(display_name_index); 
      views.nameview.settext(name); 
      views.delcheckbox.setchecked(selectedmap.get(position)); 
      // 保存记录id 
      if (selectedmap.get(position)) { 
        delcontactsidset.add(string.valueof(cur 
            .getint(contacts_id_index))); 
      } else { 
        delcontactsidset.remove(string.valueof(cur 
            .getint(contacts_id_index))); 
      } 
      return convertview; 
    } 
 
    @override 
    public int getcount() { 
      return cur.getcount(); 
    } 
 
    @override 
    public object getitem(int position) { 
      if (cur.movetoposition(position)) { 
        return cur; 
      } else { 
        return null; 
      } 
    } 
 
    @override 
    public long getitemid(int position) { 
      return position; 
    } 
  } 
 
  @override 
  public void onclick(view v) { 
    switch (v.getid()) { 
    case r.id.select_all: 
      // 全选checkbox的click事件处理 
      if (selectall.ischecked()) { 
        for (int i = 0; i < contactsdeleteadapter.getcount(); i++) { 
          contactsdeleteadapter.selectedmap.put(i, true); 
          //click事件:全选checkbox被勾选则把所有的联系人id添加到delcontactsidset中 
          contactsdeleteadapter.cur.movetoposition(i); 
          contactsdeleteadapter.delcontactsidset.add(string 
              .valueof(contactsdeleteadapter.cur 
                  .getint(contacts_id_index))); 
        } 
        contactsdelbtn.setenabled(true); 
      } else { 
        for (int i = 0; i < contactsdeleteadapter.getcount(); i++) { 
          contactsdeleteadapter.selectedmap.put(i, false); 
        } 
        //click事件:全选checkbox被取消勾选则把delcontactsidset清空 
        contactsdeleteadapter.delcontactsidset.clear(); 
        contactsdelbtn.setenabled(false); 
      } 
      contactsdeleteadapter.notifydatasetchanged(); 
      break; 
    case r.id.contacts_delete_btn: 
      new alertdialog.builder(this).settitle( 
          r.string.clearconfirmation_title).setmessage( 
          r.string.clearconfirmation).setnegativebutton( 
          android.r.string.cancel, null).setpositivebutton( 
          android.r.string.ok, new dialoginterface.onclicklistener() { 
            @override 
            public void onclick(dialoginterface dialog, int which) { 
              final progressdialog progressdialog = progressdialog 
                  .show( 
                      multiselectactivity.this, 
                      getstring(r.string.clearprogress_title), 
                      "", true, false); 
              final asynctask<void, void, void> task = new asynctask<void, void, void>() { 
                @override 
                protected void doinbackground(void... params) { 
                  // 删除记录事件处理(我这里就不写详细的代码了) 
                  return null; 
                } 
 
                @override 
                protected void onpostexecute(void result) { 
                  progressdialog.dismiss(); 
                } 
              }; 
              progressdialog.show(); 
              task.execute(); 
            } 
          }).setcancelable(true).create().show(); 
      break; 
    case r.id.contacts_cancel_btn: 
      // 取消事件处理 
      break; 
    } 
  } 
 
  @override 
  public void onitemclick(adapterview<?> arg0, view view, int position, 
      long id) { 
    log.i(tag, "onitemclick"); 
    contactsdeletelistitemviews views = (contactsdeletelistitemviews) view 
        .gettag(); 
    views.delcheckbox.toggle(); 
    contactsdeleteadapter.selectedmap.put(position, views.delcheckbox 
        .ischecked()); 
    contactsdeleteadapter.notifydatasetchanged(); 
    // 判断是否有记录没被选中,以便修改全选checkbox勾选状态 
    if (contactsdeleteadapter.selectedmap.containsvalue(false)) { 
      selectall.setchecked(false); 
    } else { 
      selectall.setchecked(true); 
    } 
    // 判断是否有记录被选中,以便设置删除按钮是否可用 
    if (contactsdeleteadapter.selectedmap.containsvalue(true)) { 
      contactsdelbtn.setenabled(true); 
    } else { 
      contactsdelbtn.setenabled(false); 
    } 
  } 
} 

布局文件:contacts_delete_activity.xml

<?xml version="1.0" encoding="utf-8"?> 
<!-- 
  zuolongsnail@163.com 
  this layout of delete contacts. 
--> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" > 
 
  <include 
    android:id="@+id/contacts_delete_list_header" 
    layout="@layout/contacts_delete_list_header" /> 
 
  <listview 
    android:id="@+id/contacts_delete_list" 
    android:layout_width="match_parent" 
    android:layout_height="0dip" 
    android:layout_weight="1" /> 
 
  <linearlayout 
    style="@android:style/buttonbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 
 
    <button 
      android:id="@+id/contacts_delete_btn" 
      android:layout_width="0dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:enabled="false" 
      android:text="@string/delete" /> 
 
    <button 
      android:id="@+id/contacts_cancel_btn" 
      android:layout_width="0dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="@string/cancel" /> 
  </linearlayout> 
 
</linearlayout> 

代码下载地址:源码下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。