Android with checkbox in the ListView for multi-Select, select All, reverse Select

Source: Internet
Author: User

Because of some features of the ListView, just start writing the function of this requirement will encounter some problems, the focus is to store the status value of each checkbox, here to share the perfect solution:   layout file: [HTML]  < XML version= "1.0" encoding= "Utf-8"?>  <relativelayout xmlns:android= "Http://schemas.android.com/apk/res /android "     android:layout_width=" fill_parent "     android:layout_height=" Fill_ Parent "     android:orientation=" Horizontal ">        <textview  & nbsp       android:id= "@+id/tv"          android:layout_width= "Fill_parent"  & nbsp       android:layout_height= "wrap_content"          android:layout_gravity= " Center_vertical "/>        <linearlayout          android:id=" @ +id/line "         android:layout_width=" fill_parent "         Android : layout_height= "50DP"          Android:layout_below= "@+id/tv"          android:orientation= "Horizontal" >    & nbsp       <button              android:id= "@+id/bt_selectall"  &nbs P           android:layout_width= "80DP"              Android:lay out_height= "Fill_parent"              android:text= "Select All"/>                  <button              android:id= "@+i D/bt_cancleselectall "             android:layout_width=" 80DP "     & nbsp       android:layout_height= "fill_parent"              android:text= " Reverse Select/>                             &nbs P     <button             android:id= "@+id/bt_deselectall"              android:layout_width= "80DP"              android:layout_height= "Fill_parent"              android:text= "deselect"/>        </ linearlayout>        <listview          android:id= "@+id/lv" & nbsp;        android:layout_width= "fill_parent"          Android:layout_ height= "Fill_parent"          android:layout_below= "@+id/line"/>    </ Relativelayout>     listview's Item layout file:  [html] <?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_tv"          Android:layout_ Width= "0DP"          android:layout_height= "wrap_content"          Android:layout_gravity= "center_vertical"          android:layout_weight= "1"/>         <checkbox          android:id= "@+id/item_cb"      & nbsp   android:layout_width= "wrap_content"          android:layout_height= "Wrap_content"          android:clickable= "false"          android:focusable= "false"          android:focusableintouchmode= "false"          Android: gravity= "Center_vertical"/>    </linearlaYout>    activity: [java]  public class Ex_checkboxactivity extends Activity {      private ListView LV;      Private Myadapter madapter;      private arraylist<string> list;      Private Button bt_selectall;      Private Button bt_cancel;      Private Button bt_deselectall;      private int checknum; Record the number of selected items      Private TextView tv_show;//used to display the number of selected items       /** called when T He activity is first created. */       @Override      public void onCreate (Bundle savedinstancestate) {          super.oncreate (savedinstancestate);          Setcontentview (R.layout.main);         /* Instantiate individual controls */         LV = (ListView) Findviewbyid (r.id.lv);          BT_selectall = (Button) Findviewbyid (R.id.bt_selectall);          Bt_cancel = (Button) Findviewbyid (R.id.bt_cancelselectall);          Bt_deselectall = (Button) Findviewbyid (R.id.bt_deselectall);          tv_show = (TextView) Findviewbyid (r.id.tv);          list = new arraylist<string> ();         //Preparing data for adapter          initdate ();         //Instantiate custom Myadapter          Madapter = new Myadapter (list, thi s);         //Binding adapter          Lv.setadapter (madapter);           //Select All button callback interface          Bt_ Selectall.setonclicklistener (New Onclicklistener () {             @Override  & nbsp           public void OnClick (ViEW v) {                //traverse the list length to set the map value in Myadapter to True    & nbsp             for (int i = 0; i < list.size (); i++) {         &NB Sp           myadapter.getisselected (). Put (I, true);                         &NB Sp The number is set to the length of list                  Checknum = List.size ();                 //Refresh the display of the ListView and TextView                  datachanged ();             }         });           //Reverse button Callback interface          Bt_ Cancel.setonclicklistener (New Onclicklistener () {           &NBSP @Override              public void OnClick (View v) {                //traverse the length of list, set selected as not selected, optional set as selected                  FO R (int i = 0; i < list.size (); i++) {                    /if (M Yadapter.getisselected (). get (i)) {                       &NBS P Myadapter.getisselected (). Put (I, false);                          checknum--;                     } else {         &NB Sp               myadapter.getisselected (). Put (I, true);                          checknum++;            &NBSP;        }                 }        & nbsp        //Refresh the display of ListView and TextView                  Datach Anged ();             }         });           //Cancel button callback interface          Bt_ Deselectall.setonclicklistener (New Onclicklistener () {             @Override  & nbsp           public void OnClick (View v) {               &N Bsp Traverse the list length to set the selected button to not selected                  for (int i = 0; i < list.size (); i++) {                     if (myadapter.getisselected (). get (i)) {                &NBsp         myadapter.getisselected (). Put (I, false);                          checknum--;//quantity minus 1                                     &N Bsp }                 //Refresh the display of the ListView and TextView        &NBSP ;         datachanged ();             }         });           //Bindings ListView Listener          Lv.setonitemclicklistener (New Onitemclicklistener () {             @Override  & nbsp           public void Onitemclick (adapterview<?> arg0, View arg1, int arg2,    &n Bsp                 long Arg3) {&NBsp;               //Get Viewholder objects, which eliminates the steps to instantiate the CB instance we need through layers of findviewbyid and nbsp;                Viewholder holder = (viewholder) arg1.gettag ();                 //Change checkbox status            &N Bsp     Holder.cb.toggle ();                 //Record checkbox selection          &NBS P       myadapter.getisselected (). Put (Arg2, holder.cb.isChecked ());                 //Adjust selected items              &N Bsp   if (holder.cb.isChecked () = True) {                    -ch ecknum++;                 } else {             &NB Sp      checknum--;                         &NB Sp TextView display                  Tv_show.settext ("checked" + checknum + "items");             }         });            //initialization data      private void Initdate () {         for (int i = 0; i < i++) {             List.add ("Data" + " "+ i);         }         ;          //Refresh the display of the ListView and TextView      private void datachanged () {&nbsp ;       //Notification ListView Refresh          madapter.notifydatasetchanged ();         //TextView show the latest selection          Tv_show.SetText ("checked" + checknum + "item");     };  }     List adapter:  [java]  package Com.notice.listcheck;    import java.util.ArrayList;  import Java.util.HashMap;    import Android.content.Context;  import Android.view.LayoutInflater;  import Android.view.View;  import Android.view.ViewGroup;  import Android.widget.BaseAdapter;  import Android.widget.CheckBox;  import Android.widget.TextView;    public class Myadapter extends Baseadapter {    //List of populated data      privat e arraylist<string> list;     //To control the check status of the checkbox      private static Hashmap<integer, boolean> isSelected;     //context      private context context;     //For importing layouts      private layoutinflater inflater = null;       //constructors      public MyadaPter (arraylist<string> list, context context) {         this.context = Context;  &nbs P       this.list = list;          Inflater = layoutinflater.from (context);          isSelected = new Hashmap<integer, boolean> ();         //initialization data          initdate ();            //Initialize isselected data      private void Initdate () {&N bsp;        for (int i = 0; i < list.size (); i++) {             Getisselected (). Put (I, false);         }     }        @Override      PU Blic int GetCount () {         return list.size ();     }        @Override      public Object getItem (int position) {         return list.get (position),     }      &nbs P @Override      Public long getitemid (int position) {         return position; &NB sp;   }        @Override      public View getView (int position, view Co Nvertview, ViewGroup parent) {         Viewholder holder = null;        &nbs P if (Convertview = = null) {            //Get Viewholder object        &N Bsp     HOLDER = new Viewholder ();             //import layouts and assign values to Convertview              con Vertview = inflater.inflate (R.layout.listviewitem, NULL);              holder.tv = (TextView) Convertview.findviewbyid (R.ID.ITEM_TV);              HOLDER.CB = (CheckBox) Convertview.findviewbyid (R.ID.ITEM_CB);             //For view settings tags              CONVERTVIEW.S Ettag (holder);         } else {            //Remove holder              holder = (viewholder) convertview.gettag ();         }         //Set TextView in list        &NB Sp Holder.tv.setText (List.get (position));         //Set checkbox selection according to isselected          holder.cb.setChecked (getisselected (). get (position));          return convertview;             public static Hashmap<integer, boolean> getisselected () {&NB sp;        return isSelected;             Publicstatic void Setisselected (Hashmap<integer, boolean> isSelected) {         myadapter.isselected = isSelected;             public static class Viewholder {         T Extview TV;          CheckBox CB;     }  }   

The ListView for Android has multiple selections, select all, and reverse the selection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.