我有一個ListView與android:choiceMode =「multipleChoice」。我通過一個SimpleCursorAdapter從一個Cursor填充這個ListView。是否真的沒有辦法直接將ListView的CheckedTextView佈局的「CheckBox」綁定到光標的布爾值?如何將multipleChoice ListView中的CheckBox與SimpleCursorAdapter綁定爲布爾值?
private void showMyData(long myId) {
// fill the list
String[] fromColumns = { "myTextColumn" };
int[] toViews = { android.R.id.text1 };
Cursor myCursor = _myData.readData(myId);
CursorAdapter myAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_multiple_choice,
myCursor, fromColumns, toViews);
ListView myListView = (ListView) findViewById(R.id.myListView);
myListView.setAdapter(myAdapter);
// mark items that include the object specified by myId
int myBooleanColumnPosition = myCursor
.getColumnIndex("myBooleanColumn");
for (int i = 0; i < myCursor.getCount(); i++) {
myCursor.moveToPosition(i);
if (myCursor.getInt(myBooleanColumnPosition) == 1) {
myListView.setItemChecked(i, true);
}
}
}
,沒有工作:
通過遊標調用ListView.setItemChecked()如果值爲true,則目前我循環。但我想要這樣的代碼:
String[] fromColumns = { "myTextColumn", "myBooleanColumn" };
int[] toViews = { android.R.id.text1, android.R.id.Xyz };
並且沒有循環。我在這裏錯過了什麼,或者它是Android?
編輯: 我想這是建議的Luksprog:
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
CheckedTextView ctv = (CheckedTextView) view;
ctv.setText(cursor.getString(cursor
.getColumnIndex("myTextColumn")));
if (cursor.getInt(cursor.getColumnIndex("myBooleanColumn")) == 1) {
ctv.setChecked(true);
Log.d("MY_TAG", "CheckBox checked");
}
return true;
}
這記錄勾選複選框,但實際上確實沒有做到這一點。也許這是我的一個錯誤。雖然它至少比初始循環更復雜,但感覺就像是使用框架,而不是反對它。所以謝謝你的答案。
但總結一下:Android實際上缺少直接的方法。
你只需要使用一個'id'的'toViews'陣列中(只是使用'android.R.id.text1')?還要在其中設置未選中狀態的「else」子句。這應該至少在列表中直觀地工作。請記住,我的答案將強制ListView只保留Cursor中的CheckBoxes的狀態,您所做的任何更改都需要Cursor在列表中顯示。我會用你最初的方法循環運行一次並不壞。 – Luksprog
simple_list_item_multiple_choice.xml僅包含單個視圖(text1) - 這就是問題所在。 我會堅持循環,因爲它似乎是官方的方式。我只是在學習API,並且希望能夠舒舒服服地說,我沒有錯過任何東西,因爲這個循環看起來像拼湊在一起。 setItemChecked()更新LongSparseArray並調用一個回調函數,如果某個項目不可見,我猜測它什麼也不做。因此,即使對於大量的項目,也可以運行此循環。 – Rhyme