Transferred from: http://www.cnblogs.com/wujd/archive/2012/08/17/2635309.html
When a checkbox is included in a ListView, there is often a problem with checkbox confusion, most of the time the code is as follows:
Look first: Odd behavior selected, even behavior unchecked
Specific code:
Layout file:
1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "3 android:layout_width=" fill_parent "4 android:layout_height=" Fill_parent "5 Android:o rientation= "Horizontal" > 6 7 <linearlayout 8 android:id= "@+id/layout" 9 android:layout _width= "Fill_parent" android:layout_height= "fill_parent" >11- <textview android: Id= "@+id/textview" android:layout_width= "wrap_content" android:layout_height= wrap_content "/>" <checkbox android:id= "@+id/checkbox" android:layout_width= "Wrap_content" 20 android:layout_height= "wrap_content"/>21 </linearlayout>23 </ Linearlayout>
JAVA CODE:
1 package Com.tony.ui.listview; 2 3 Import java.util.ArrayList; 4 Import java.util.List; 5 6 Import COM.TONY.R; 7 8 Import android.app.Activity; 9 Import Android.os.Bundle; Ten import Android.view.LayoutInflater; Import Android.view.View; Import Android.view.ViewGroup; Import Android.widget.BaseAdapter; Import Android.widget.CheckBox; Android.widget.CompoundButton import; Android.widget.CompoundButton.OnCheckedChangeListener import; + Import Android.widget.LinearLayout; Import Android.widget.ListView; Import Android.widget.TextView; public class Listviewcheckbox extends activity{, private listview ListView, Private list<a& Gt List Private Adapter1 Adapter1; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedinstan Cestate); Setcontentview (R.layout.listview_checkbox); Initdate (); ListView = (ListView) Findviewbyid (R.ID.listview); Adapter1 = new Adapter1 (); Listview.setadapter (Adapter1); 35} 36 37 38/** 39 * Simulates 40 data, odd data is selected, even data is unchecked (+/-initdate) {42 List = new arraylist<a> (); A A; i=0;i<40;i++ (int) {i%2==0) {47 A = new A (i+ ", a.type_nochecked); List.add (a); }else{a = new A (i+ "number", a.type_checked); List.add (a); 51 } Adapter1 extends baseadapter{----@Override GetCount () {list.size return (); @Override (), and the public Object getItem (int Position) {"Return null", "n}" @Override "Getitemid" (int positi On) {return 0; @OverrideW GetView (int position, View Convertview, ViewGroup parent) {The final int index = position; Ewholder Viewholder; if (Convertview = = null) {Viewholder = new Viewholder (); Convertview = Layoutinflater.from (Listviewcheckbox.this). Inflate (R.layout.listview_checkbox_item, NULL); Viewholder.layout = (linearlayout) Convertview.findviewbyid (r.id.layout); Viewholder.textview = (TextView) Convertview.findviewbyid (R.id.textview); Bayi Viewholder.checkbox = (checkBox) Convertview.findviewbyid (R.id.checkbox); Convertview.settag (Viewholder); }else{Viewholder = (viewholder) Convertview.gettag (); 85} 86 8 7 ViewHolder.textView.setText (List.get (position). Name); if (List.get (position). Type = = a.type_checked) {ViewHolder.checkBox.setCheckeD (TRUE); }else{viewHolder.checkBox.setChecked (FALSE); 93} 94 95 /* Click on the checkbox to change the checkbox status *//*final viewholder vv = Viewholder; ViewHolder.layout.setOnClickListener (New Onclicklistener () {98 @Override 99 public void OnClick (View v) {vv.checkBox.isChecked ()) {101 Vv.checkbox . setchecked (false); 102 List.get (index). Type = type_checked;103}else{104 Vv.checkBox.setChecked (True); List.get (index). Type = type_nochecked;106 }107 108}109}); */110 111 Viewhol Der.checkBox.setOnCheckedChangeListener (New Oncheckedchangelistener () {@Override113 PU Blic void OnCheckedChanged (Compoundbutton buttonviEW, Boolean isChecked) {isChecked) {list.get (index). Type = A.type_ch ecked;116}else{117 list.get (index). Type = a.type_nochecked;118 }119}120}); 121 122 return convertview;123}124}12 5 126 class viewholder{127 linearlayout layout;128 TextView textview;129 checkbox checkbox }131-Class A {133 134 public static final int type_checked = 1;135 public sta Tic Final int type_nochecked = 0;136 137 String name;138 int type;139 public A (String name,int type) {141 THIS.name = name;142 This.type = type;143}144}145}
The code above is to set whether the checkbox is selected based on the type of object in the list collection, and when the user taps the checkbox, the program saves its state to the list collection object, depending on whether the checkbox is selected. It is believed that many people will be confident when they do it for the first time that such logic is perfectly flawless. But as a result, the test did not click the checkbox to change its state, but simply pull up and down the ListView when it will be found, as if things are not as simple as imagined.
As follows:
As long as the eyesight is not too poor people can see, according to the logic of the program how to continuously two checkboxes of the state will be the same, well, it must be the simulator insanity.
Solution:
The two solutions that many people give
1: Come up to say is because Convertview object common reason, cannot use Convetview, but each time GetView () The time is new an object's view come out. This is probably the way to get out of the butt.
2: That is, then I'm going to make a collection of my own. Save checkbox State, then confusion, kill you. Then there is a list in the adapter to save the checkbox state, why do you want to save the state of the checkbox, not superfluous it?
PS: Neither of these approaches explains why the disorder is in the first order. Here's an attempt to analyze:
1: First analysis under ViewHolder.checkBox.setOnCheckedChangeListener (New Oncheckedchangelistener () ...);
The sentence is to add a listener to the checkbox, and if the checkbox state changes, the system will automatically call back the Oncheckedchange () method.
The Oncheckedchange () method in this article is the code that records the checkbox state after this change.
2: Then analyze the next if (List.get (position). Type = = a.type_checked) {...}, this part of the code is based on the object property in the list collection to initialize the View checkbox should be the selection state.
3: When I swipe up and down the ListView, the checkbox is in a state of confusion, according to the 2nd analysis, regardless of the status of the checkbox will not be chaotic, unless the list of objects in the collection of properties has been changed, in the end where the change it?
4: There is only one place in the text that changes the properties of the CheckBox object in the list collection, which is the Oncheckedchangelistener () method mentioned in the 1th. It was carried out?
What's going on, it's impossible, hit a breakpoint, run and then you know when you swipe up and down the ListView does stop.
5: This is the function of Convertview, because no matter how many data are displayed in the ListView, only a few objects are shared, and our code re-assigns the resulting object every time.
Right, it is in this assignment when the problem, assuming that the Android system to generate 10 of the common view object, the first view object in the first screen should be displayed as "not selected" state, and to the second screen, but to display as "select" state, but because it is the same object shared, According to the 1th, the Oncheckedchange () method is called when the status of the checkbox changes.
6: Maybe someone will suspect that even if it calls the OnCheckedChanged () method, then what? The code in the Oncheckedchange () method still saves the current selection to the list collection, When I show it again, it will be displayed correctly according to the code mentioned in the 2nd, yes, the code will change the properties of the list group according to the current index. The key is here, is this index really right? Test it and know:
Print index in the Oncheckedchange () method, and when you swipe down quickly, the value of index is as follows:
7: There are 10 common objects (for example, not necessarily), when the Oncheckedchange () method is called, at least when the common object is exhausted, and then the first common object is used to print, then the index should be starting from 10, Why does 0 appear in the printed results?
8: This is due to the order of the Code, as can be seen from the code above, the code to add the listener after initializing the CheckBox property code, that is, when the CheckBox property is initialized, because it may change its state, causing the call to the Oncheckedchange () method, And this listener is added at the time of the last initialization, then of course its index is the last Positon value, not this time, so each time you save the checkbox attribute state, you assign the value to the list of other objects in the collection, Rather than the object associated with this index, this is the real reason for the confusion.
9: Workaround: As the result of the index error, so long as the index value and the current positon to maintain a can, Simply add the listener's method to the code that initializes the checkbox state in view. This is where the Oncheckedchange () method is called because of initialization, and because the index value is up-to-date, it is still not garbled.
code example:
1 class Adapter1 extends baseadapter{2 3 @Override 4 public int GetCount () {5 return list. Size (); 6} 7 8 @Override 9 public Object getItem (int position) {Ten return null;11}1 2 @Override14 public long getitemid (int position) {0;16}17 @O Verride19 public View getView (int position, view Convertview, ViewGroup parent) {Final int index = Position;21 Viewholder viewholder;22 if (Convertview = = null) {Viewholder = new V Iewholder (); Convertview = Layoutinflater.from (listviewcheckbox.this). Inflate (R.layout.listview_checkbox _item, null); viewholder.layout = (linearlayout) Convertview.findviewbyid (r.id.layout); 26 Viewholder.textview = (TextView) Convertview.findviewbyid (r.id.textview); Viewholder.checkbox = (CheckBo x) convertview.fiNdviewbyid (R.id.checkbox); Convertview.settag (Viewholder);}else{30 viewho Lder = (Viewholder) convertview.gettag ();}32 ViewHolder.checkBox.setOnCheckedChan Gelistener (New Oncheckedchangelistener () {@Override35 public void oncheckedchanged (Comp Oundbutton Buttonview, Boolean isChecked) {$ if (isChecked) {Notoginseng list.get (index) . Type = a.type_checked;38}else{39 list.get (index). Type = a.type_nochecked;40 }41}42}); ViewHolder.textView.setText (list. Get (position). Name), List.get if (position). Type = = a.type_checked) {viewHolder.checkBox.se Tchecked (true);}else{48 viewHolder.checkBox.setChecked (false); 49}50 Return convertview;51 }52}
Summarize:
In fact, the solution is a word, "Just add the listener method to initialize the view in the checkbox state code before." "