listview setItemChecked doesn't work
Asked Answered
S

1

12

For some reason setItemChecked doesn't work. can some one help me fix ti ?

String[] str = getResources().getStringArray(R.array.brush_type);
sizeArrayAdapter = new ArrayAdapter<String>(this.getContext(), R.layout.drawing_list_item, str);

listType = SIZE_LIST;
listView.setAdapter(sizeArrayAdapter);

// Populate the listView
listView.setItemChecked(4,true);

and this is the list item:

<CheckedTextView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawingCheckedTextView"
        android:layout_width="fill_parent"
        android:layout_height="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:checkMark="?android:attr/listChoiceIndicatorSingle"
        android:background="@drawable/list_panel"
        android:paddingLeft="6dip"
        android:paddingRight="6dip"/>

please help me.

Simonette answered 14/3, 2011 at 19:34 Comment(2)
You have to implement Checkable Interface too. See my answer here: https://mcmap.net/q/401814/-listview-setitemchecked-only-works-with-standard-arrayadapter-does-not-work-when-using-customized-arrayadapterInclining
CheckedTextView already implements it, as stated here: developer.android.com/reference/android/widget/… An extension to TextView that supports the Checkable interface.Houseline
C
16

The docs say this:

Sets the checked state of the specified position. The is only valid if the choice mode has been set to CHOICE_MODE_SINGLE or CHOICE_MODE_MULTIPLE.

So you might try:

list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

before calling setItemChecked.

Cryptozoite answered 14/3, 2011 at 20:16 Comment(1)
I naively thought using android.R.layout.simple_list_item_single_choice would take care of this, but I guess as I'm learning it should be obvious that setting the layout doesn't set the actual behavior at all?Craigie

© 2022 - 2024 — McMap. All rights reserved.