Advanced Android UI multi-select and record of checkbox in ListView

Source: Internet
Author: User

Today we continue to share with you the contents of the ListView. In many cases, we use the ListView and CheckBox mates to provide the user with some selection actions. For example, on a list page, we need to record which entries the user has checked. The implementation of this is not too difficult, but there are a lot of friends to ask me how to achieve, they have encountered a variety of problems, this is written together to share with you.

The ListView operation will definitely involve the item and the adapter, and we'll go ahead and implement this part.

First, write an XML layout of item, with a TextView and a checkbox inside. To be aware, here I set the checkbox to have no focus, so that you cannot click the checkbox individually, but after clicking on the ListView entry, the checkbox responds to the action.

 
<?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:o rientation= "Horizontal" >    <textview        android:id= "@+id/item_tv"        android:layout_width= "0DP"        android:layout_height= "Wrap_content"        android:layout_weight= "1"        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>

The following is a adapter class, we still inherit the Baseadapter class. Here we use a hashmap<integer,boolean> key value to record the checkbox's selection at the corresponding location, which is the basis of this example implementation.

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{//fill data listprivate arraylist<string> list;//is used to control the check state of a checkbox private static hashmap< Integer,boolean> isselected;//Context Private context context;//used to import layout private Layoutinflater Inflater = null;// Constructor public Myadapter (arraylist<string> list, context context) {This.context = Context;this.list = List;inflater = La Youtinflater.from (context); isSelected = new Hashmap<integer, boolean> ();//Initialize Data initdate ();} Initializes the isselected data private void Initdate () {for (int i=0; i<list.size (); i++) {getisselected (). put (I,false);}} @Overridepublic int GetCount () {return list.size ();} @Overridepublic Object getItem (int position) {return List.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder = null;if (Convertview = = null) {//Get Viewholder Object holder = new Viewholder ();//import layout and assign value to Convertviewconvertview = Inflater.inflate ( R.layout.listviewitem, null); holder.tv = (TextView) Convertview.findviewbyid (R.ID.ITEM_TV); HOLDER.CB = (CheckBox) Convertview.findviewbyid (R.ID.ITEM_CB);//Set label for View Convertview.settag (holder);} else {//Remove Holderholder = (viewholder) Convertview.gettag ();} Sets the display Holder.tv.setText (list.get (position)) of the TextView in the list, and/or sets the check status of the checkbox according to IsSelected holder.cb.setChecked ( Getisselected (). get (position)); return Convertview;} public static hashmap<integer,boolean> getisselected () {return isSelected;} public static void setisselected (Hashmap<integer,boolean> isSelected) {myadapter.isselected = isSelected;}}

The comments have been written in great detail, by

Holder.cb.setChecked (getisselected (). get (position));

This line of code allows us to set the checkbox to the selected state.

Then we just need to control the isselected's key value in the Click event to control the check of the corresponding position checkbox.

In addition to the activity we placed a ListView, but also placed three buttons, respectively, to achieve a full selection, cancellation and inverse selection.

Look at the code for the Activity class:

Package Com.notice.listcheck;import Java.util.arraylist;import Android.app.activity;import android.os.Bundle; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.button;import Android.widget.ListView;    Import Android.widget.textview;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;//is used to display the selected number of items/** called when the 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> ();        Prepare data for Adapter initdate ();        Instantiates the custom Myadapter Madapter = new Myadapter (list, this);        Binding Adapter Lv.setadapter (Madapter); Callback interface for the Select All button Bt_selectall.setonclicklistener (new Onclicklistener () {@Override public void on Click (View v) {//traverse the length of list to set all map values in Myadapter to True for (int i = 0; i < list.size (); i+                +) {myadapter.getisselected (). Put (I, true);                }//Quantity set to list length Checknum = List.size ();            Refreshes the display of the ListView and TextView datachanged ();        }        });           Callback interface for the Cancel button Bt_cancel.setonclicklistener (new Onclicklistener () { @Override public void OnClick (View v) {//iterates through the length of the list, sets the selected button to not selected for (int i = 0; I < list.size (); i++) {if (myadapter.getisselected (). get (i)) {myadapter.getisselected (). put (I,                        FALSE); checknum--;//number minus 1}}//Refresh the display of the ListView and TextView Datachang            Ed ();        }        }); Callback Interface Bt_deselectall.setonclicklistener (new Onclicklistener () {@Override public void for the counter-selection button                    OnClick (View v) {//Traverse list length, set selected as unchecked, unchecked to selected for (int i = 0; i < list.size (); i++) {                        if (myadapter.getisselected (). get (i)) {myadapter.getisselected (). Put (I, false);                    checknum--;                        } else {myadapter.getisselected (). Put (I, true);                    checknum++;}}//Refresh the ListView and TextView display datachanged ();                }        });  Binding the ListView Listener Lv.setonitemclicklistener (New Onitemclicklistener () {@Override public void Onitemclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {//Get Viewholde                R object, which eliminates the steps to instantiate the CB instance we need through layers of Findviewbyid viewholder holder = (viewholder) arg1.gettag ();                Change the status of the CheckBox Holder.cb.toggle ();                 Record the check status of the CheckBox myadapter.getisselected (). Put (Arg2, holder.cb.isChecked ());                Adjusts the selected entry if (holder.cb.isChecked () = = true) {checknum++;                } else {checknum--;                            }//Display Tv_show.settext with TextView ("Selected" +checknum+ "item");    }        }); }//Initialize data private void Initdate (){for (int i = 0; i < i++) {List.add ("data" + "" + i); }}//Refresh ListView and TextView display private void datachanged () {//Notify ListView Refresh Madapter.notifydatasetch        Anged ();    TextView Displays the most recent selected number Tv_show.settext ("checked" + checknum + "item"); }    }

In the code in the Click event of item, call directly

Holder.cb.toggle ();

Change the status of the checkbox, then save the value in the map record

Myadapter.getisselected (). Put (Arg2, holder.cb.isChecked ());

A few other button click events, all by traversing the length of the list to set the value of IsSelected, and then notify the ListView based on the changed adapter refresh, to achieve the corresponding check state of the checkbox. Because we still use viewholder to optimize the efficiency of the ListView in the processing of the ListView.

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.