I need your help. I’m really new to Android, developing in Eclipse with the latest 2.1 SDK.
This is really simple. I make a ListView which is filled with Checkbox widgets.
My code:
public class HelloAndroid extends Activity {
static final String[] COUNTRIES = new String[] {
"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
"Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
"Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
"Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium"};
protected ListView myList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList = (ListView)findViewById(R.id.myList);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this, R.layout.row, R.id.myBox, COUNTRIES);
myList.setAdapter(myAdapter);
}
}
And this is the Layout-XML-file (row.xml), consisting of a single checkbox:
<?xml version="1.0" encoding="utf-8"?>
<CheckBox
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
Now if there are enough strings in the COUNTRIES-Array and you can scroll the List, you will see, that if you check one CheckBox and scroll down, some another CheckBox gets checked automatically. And if you check some more boxes, more get checked automatically, or ones that were checked get unchecked.
I’ve also tried android:focusable="false" for the CheckBox (in the XML), as well as android:focusableInTouchMode, as described in some similar threads, but nothing seems to help…
Looks like its a bug??
What’s happening is that Android is reusing the
CheckBoxviews it creates to display the list to save memory. Instead of creating a newCheckBoxfor every item in your list, Android creates just enough to fill the screen, updating them to show the relevant data for the items which are currently visible.If you have no link between the data in your Adapter and the state of the CheckBox in the view then it will appear that lots of CheckBoxes are linked, when in fact it’s the same CheckBox with a different label.
Have you set the
choiceModeattribute of yourListView? If you do, this will tell theListViewto keep track of what you have selected.Also, consider using the
CheckedTextViewclass instead ofCheckBox.