2011-03-14 86 views
10

出於某種原因,setItemChecked不起作用。有人能幫我修理嗎?listview setItemChecked不起作用

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); 

,這是列表項:

<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"/> 

請幫助我。

+1

你也必須實現Checkable接口。看到我的答案在這裏:http://stackoverflow.com/a/19997650/1361494 – moondroid 2013-11-15 09:31:47

+0

'CheckedTextView'已經實現它,如下所述:https://developer.android.com/reference/android/widget/CheckedTextView.html'支持Checkable接口的TextView的擴展.' – 2017-09-08 09:43:04

回答

15

docs這樣說:

設置 指定位置的選中狀態。如果選擇模式設置爲 CHOICE_MODE_SINGLE或 CHOICE_MODE_MULTIPLE,則僅有效的 。

所以,你可以嘗試:

list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 

調用setItemChecked之前。

+0

我天真地認爲使用android.R.layout.simple_list_item_single_choice會照顧這一點,但我想我正在學習它應該是顯而易見的設置佈局不設置實際的行爲呢? – Chinasaur 2011-07-22 17:50:26