Android UI: How to Select multiple checkbox and record in listview

Source: Internet
Author: User

I will continue to share with you the content related to listview today. In many cases, listview and checkbox are used together to provide users with some selection operations. For example, on a configuration page, we need to record the items selected by the user. This implementation is not too difficult, but many of my friends have asked me how to implement it. They have encountered various problems and I will write them here to share them with you.

The listview operation will certainly involve item and adapter. We should first implement this part.

First, write the XML layout of an item, which contains a textview and a checkbox. Note that there is no focus in the checkbox. In this case, you cannot click checkbox separately. Instead, after you click the listview entry, the checkbox will respond to the operation.

<?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_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>

Write an adapter class below, and we still inherit the baseadapter class. Here, we use a hashmap <integer, Boolean> key value to record the checkbox selection status at the corresponding position, which is the basis of implementation in this example.

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 {// The listprivate arraylist <string> List of filled data; // It is used to control the selected status of the checkbox Private Static hashmap <integer, Boolean> isselected; // context private context; // used to import the layout private layoutinflater Inflater = NULL; // constructor public myadapter (arraylist <string> list, context) {This. context = context; this. list = List; Inflater = layoutinflater. from (context); isselected = new hashmap <integer, Boolean> (); // initialize data initdate () ;}// initialize 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) {// obtain the viewholder object holder = new viewholder (); // import the layout and assign it 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 the label convertview for the view. settag (holder);} else {// retrieve holderholder = (viewholder) convertview. gettag () ;}// set the display of textview in the list to holder. TV. settext (list. get (position); // set the checkbox selection status based on 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 comment has been written in very detail.

holder.cb.setChecked(getIsSelected().get(position));

This line of code sets the checkbox selection.

In this case, you only need to control the isselected key value in the click event to control the checkbox selection of the corresponding position.

In the activity, in addition to placing a listview, we also put three buttons to achieve full selection, cancellation, and inverse selection respectively.

Check the code of 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 activi Ty {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 entries private textview TV _show; // used to display the number of selected entries/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcont Entview (R. layout. main);/* instantiate each control */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 the data initdate () for the adapter; // instantiate the custom myadapter madapter = new myadap Ter (list, this); // bind the adapter LV. setadapter (madapter); // callback interface bt_selectall.setonclicklistener (New onclicklistener () {@ override public void onclick (view v) {// traverses the length of the list, set all MAP values in myadapter to true for (INT I = 0; I <list. size (); I ++) {myadapter. getisselected (). put (I, true);} // The number is set to the length of the list checknum = List. size (); // refresh the display datachanged () ;}} of listview and textview; // call back bt_cancel.setoncl of the cancel button Icklistener (New onclicklistener () {@ override public void onclick (view v) {// traverses the length of the list and sets the selected button to unselected for (INT I = 0; I <list. size (); I ++) {If (myadapter. getisselected (). get (I) {myadapter. getisselected (). put (I, false); checknum --; // quantity minus 1} // refresh the display datachanged () ;}} of listview and textview ();}}); // callback interface bt_deselectall.setonclicklistener (New onclicklistener () {@ override public void onclick (view V) {// Traverse the length of the list and set the selected to unselected and unselected to the 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 display datachanged () ;}} of listview and textview; // bind the listener LV of listview. setonitemclicklistener (New onitemclicklistener () {@ override public void onitemclick (adapterview <?> Arg0, view arg1, int arg2, long arg3) {// get the viewholder object, in this way, the step viewholder holder = (viewholder) arg1.gettag (); // Changes the status of the checkbox Holder through findviewbyid. CB. toggle (); // record the checkbox selection status to myadapter. getisselected (). put (arg2, Holder. CB. ischecked (); // adjust the selected entry if (holder. CB. ischecked () = true) {checknum ++;} else {checknum --;} // use textview to display TV _show.settext ("selected" + checknum + "item") ;}}// initialize private void initdate () {for (INT I = 0; I <15; I ++) {list. add ("data" + "" + I) ;}// refresh the private void datachanged () display of listview and textview {// notify listview to refresh madapter. notifydatasetchanged (); // textview displays the latest selected number TV _show.settext ("selected" + checknum + "item ");}}


In the code, the Click Event of the item is called directly.

 holder.cb.toggle();

First, change the checkbox status and save the value to the map record.

 MyAdapter.getIsSelected().put(arg2, holder.cb.isChecked());

The other Click events of several buttons are to set the isselected value by traversing the length of the list, and then notify the listview to refresh according to the changed adapter to achieve the corresponding checkbox selected status. Because we still use viewholder to optimize the listview efficiency during listview processing (it is time-consuming to search through findviewbyid layers, if you are not familiar with listview ?, ).

Finally, let's look at the running effect:

 

 

Now, write it here. I believe everyone can understand it. Here we will talk about the next question. Many friends leave a message or send emails to some source code in the blog. I declare here that I will not send any source code of the instance that I think has been very clear about in my blog. Some instances have already posted all the code, someone still needs the source code... I hope all my friends who read my blog can really understand this instance and learn more about it. I 'd better have my own improvements and share them with you. Many of my friends are used to using other people's source code and directly move their functions to their own projects. This is a bad habit. You can learn more about it by writing more.

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.