The Android ListView plus checkbox implements the tick information for a single save checkbox

Source: Internet
Author: User

A recent project to increase the Android side of a function, is to add an activity with a lot of checkboxes on the tick information, and then you can choose the multi-box, it seems very simple. But it's a lot of trouble to really do it.

Although I have a little knowledge of Android, have seen some code, but are looking at someone else's code, see the code is of course simple, this should be all their own writing, this is a bit tricky, a start really do not know Ah, and then went online to check a bit, I think there is a personal writing good, is to use the ListView to import the layout of the adapter, so I followed his code of the prototype began to change up.


Changed n long, finally changed a little look, which also spent a lot of energy!! So when it is hot first recorded, lest later forget, forget to write again that is a thing times work half!


My newly added code has four files, each of which is adapter.java,listviewdemo,java,choice.xml,problem_item.xml four files.


Problems encountered and solutions:

1. The new multi-box selected after jumping to another interface and then click again after the interface, the previous multi-box information can not be saved, so that the selection of information can not be recorded.

Solution: Apply preference to save, the multi-Box selection information is written into the preference after the next time again into the interface and then read the initialization information to read the previous record information. The record of the multi-box is then ticked.


2.preference can only be saved with key-value pairs, and when the activity has multiple other message boxes called, it will not be able to record all the multi-marquee selection information, for example, as if there are 100 students, you want to do a multi-box for each student's category, For example, choose course subjects and so on, which activity of the subject is the same, but the data is not the same, so you need to save the multi-box data, save a good, but to save everyone's information, you need to move a brain.

Solution: Send each student's ID to the selection box activity, each time you open read the corresponding student ID for the key value, because the multi box, so there are multiple values, in order to facilitate me to convert all the multi-box to 01 string, 0 is not selected, 1 is selected. And then parse out whether or not to be selected.


The following is the corresponding function code, for reference only, insufficient hope to point out:

Adapter.java

public class Adapter extends baseadapter{private arraylist<string> list;//fill data listprivate static hashmap< Integer,boolean> isselected;//used to control the selection of a CheckBox private context context;//context private Layoutinflater Inflater=null ;//used to import layout public Adapter (arraylist<string> list,context Context)//constructor {this.context = Context;this.list = list; Inflater = Layoutinflater.from (context); isSelected = new Hashmap<integer, boolean> (); Initdate ();//initialization Data}//initialization selection is determined as falseprivate void Initdate () {for (int i=0;i<list.size (); i++) {Isselected.put (I, false);}} @Overridepublic int GetCount () {//TODO auto-generated method Stubreturn list.size ();} @Overridepublic Object getItem (int position) {//TODO auto-generated method Stubreturn list.get (position);} @Overridepublic long Getitemid (int position) {//TODO auto-generated method Stubreturn position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {//TODO auto-generated method Stubviewhold ER holder = null;if (convertvieW==null) {holder = new Viewholder (); convertview=inflater.inflate (r.layout.problem_item,null);// Import layout and assign to Convertviewholder.tv = (TextView) Convertview.findviewbyid (R.ID.ITEM_TV);//fault Message HOLDER.CB = (CheckBox) Convertview.findviewbyid (R.ID.ITEM_CB);//Tick Box Convertview.settag (holder);} Else{holder = (Viewholder) Convertview.gettag ();}          Sets the display Holder.tv.setText (list.get (position)) of the TextView in the list;          Sets the checkbox's check state holder.cb.setChecked (getisselected (). get (position)) based on isselected;  return convertview;      }public static hashmap<integer,boolean> getisselected () {return isSelected;       } public static void Setisselected (Hashmap<integer,boolean> isSelected) {adapter.isselected = isSelected;   }

Listviewdemo.java

public class Listviewdemo extends Activity {private ListView LV;      Private Adapter Madapter;      Private arraylist<string> list;      Private Button Bt_selectall;      Private Button Bt_cancel;      Private Button Bt_deselectall;    Private Button Bt_yes; private int checknum; Record the number of selected items private TextView tv_show;//is used to display the number of selected items private int id;//message number, used to store the fault designator, from the previous interface, private String D Efaul= "";//default all do not tick private String selectall= "";//Check all/** called when the activity is first created.          */@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                  Setcontentview (R.layout.choice); Intent i=getintent ();                Bundle B=i.getbundleextra ("id"); Id=b.getint ("id");          /* Instantiate individual controls */LV = (ListView) Findviewbyid (r.id.list);          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_yes= (Button) Findviewbyid (R.id.ok);          Tv_show = (TextView) Findviewbyid (r.id.tv);                   List = new arraylist<string> ();                  Initdate ();    Initializes the Tick box information, by default it is unchecked as unit for (int n=0;n<list.size (); n++) {defaul =defaul + "0";    Selectall= SelectAll + "1";          }//Prepare data for Adapter//Instantiate custom Myadapter Madapter = new Adapter (list, this);          Binding Adapter Lv.setadapter (Madapter); Getcheck ();//Get information, also can be said initialization information///////////////Select button Callback interface Bt_selectall.setonclicklistener (new onclicklist Ener () {@Override public void OnClick (View v) {//iterates through the length of the list, myadapter the map The values are all set to True for (int i = 0; i < list.size (); i++) {adapter.getisselected (). Put (                               I, true);     }//Quantity set to the length of list             Checknum = List.size ();                Refreshes the display of the ListView and TextView datachanged ();          }          }); Callback Interface for Cancel button Bt_cancel.setonclicklistener (new Onclicklistener () {@Override public vo                                                      ID OnClick (View v) {//Traverse list length, set selected button to not selected for (int i = 0; i < list.size (); i++) { if (adapter.getisselected (). get (i)) {Adapte                          R.getisselected (). Put (I, false); checknum--;//number minus 1}}//Refresh the display of the ListView and TextView/                /datachanged ();            }          }); Callback interface for the Bt_deselectall.setonclicklistener button (new Onclicklistener () {@Override Publ IC void OnClick (View v) {//Traverse list length, set selected as unchecked, unchecked to selected for (int i = 0; i < list.size (); i++) {if (adapter.getisselected (). get (i)) {adapter.getisselected (). put (I,                             FALSE);                      checknum--;                               } else {adapter.getisselected (). Put (I, true);                      checknum++;              }}//Refresh the ListView and TextView display//datachanged ();                  }          }); Determines the button returned Bt_yes.setonclicklistener (new Onclicklistener () {@Override public vo ID OnClick (View v) {String str= "";//determine to write the information directly preference save for the next read use for (i NT I=0;i<list.size (); i++) {if (adapter.getisselected (). get (i)) {str= str+ '            1 ';            } else {str = str+ ' 0 '; }} savecheck (String.valueof (ID), str);//WillData is saved as a string, and the next time it is read with finish ();                    }          }); Bind the ListView Listener Lv.setonitemclicklistener (New Onitemclicklistener () {@Override Publ IC void Onitemclick (adapterview<?> arg0, View arg1, int arg2, long arg3) {//                  The Viewholder object is obtained, thus eliminating the step viewholder holder = (viewholder) Arg1.gettag () to instantiate the CB instance we need through layers of findviewbyid;                  Change the status of the CheckBox Holder.cb.toggle ();                                            Record the check status of the CheckBox adapter.getisselected (). Put (Arg2, holder.cb.isChecked ()); Adjust the selected entry if (holder.cb.isChecked ()                 = = True) {checknum++;                  } else {checknum--;          }//Display//tv_show.settext with TextView ("Selected" +checknum+ "item");                      }          }); }//Get the data stored in this activity public void Getcheck () {sharedpreferences MPERFERENCES=PREFERENCEMANAGER.G Etdefaultsharedpreferences (this);//Get the default preference//Get Activity Private preference sharedpreferences m_private=this.ge    Tpreferences (mode_private); String counter=mperferences.getstring (string.valueof (ID), defaul);//If not, the default is 0 for (int i=0;i<list.size (); i++    {if (Counter.charat (i) = = ' 1 ') {adapter.getisselected (). Put (I, true); }}}//save data to be saved public void Savecheck (String id,string data) {//Save Shuju Sharedprefe        Rences mperferences=preferencemanager.getdefaultsharedpreferences (this);    Sharedpreferences m_private=this.getpreferences (mode_private);         Sharedpreferences.editor Meditor=mperferences.edit ();    Meditor.putstring (ID, data);    Meditor.commit ();  }//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.not          Ifydatasetchanged ();  TextView Displays the most recent selected number//tv_show.settext ("checked" + checknum + "item");    This function is not perfect, save and then open not to save this in, will be wrong.   }

Choic.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "vertical"       Android:layout_width= "Fill_parent" android:layout_height= "fill_parent" > <listview android:id= "@+id/list" Android:layout_width= "Fill_parent" android:layout_height= "400DP"/> <textview android:id= "@ +id/tv "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:layout_below         = "@+id/bt_selectall" android:gravity= "center"/> <button android:id= "@+id/bt_selectall" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@+id/lis T "android:layout_gravity=" bottom "android:text=" Select All "/> <button android:id=" @+id/bt_canc Elselectall "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout _torightof= "@+id/bt_selectall"         android:layout_below= "@+id/list" android:text= "deselect"/> <button android:id= "@+id/bt_dese Lectall "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:layout_belo w= "@+id/list" android:layout_torightof= "@+id/bt_cancelselectall" android:text= "Reverse selection"/> <But        ton android:id= "@+id/ok" android:layout_width= "wrap_content" android:layout_height= "Wrap_content"      android:layout_below= "@+id/list" android:layout_torightof= "@+id/bt_deselectall" android:text= "OK"/> </RelativeLayout>

Problem_item.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: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>

Viewholder.java

public class Viewholder {public      TextView TV = null;      Public CheckBox cb = NULL;  }  

The following are the options



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.