Android: How to set List item checked?

大憨熊 提交于 2019-12-23 04:06:16

问题


I have an android.R.layout.simple_list_item_multiple_choice with checkboxes an want so initiate some of them. How can I do that? I have the following code:

    private void fillList() {
    Cursor NotesCursor = mDbHelper.fetchAllNotes();
    startManagingCursor(NotesCursor);

    String[] from = new String[] { NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_BODY, NotesDbAdapter.KEY_CHECKED };

    int[] to = new int[] { 
    android.R.id.text1, 
    android.R.id.text2, 
    //How set checked or not checked?
     };

    SimpleCursorAdapter notes = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, NotesCursor,
            from, to);
    setListAdapter(notes);

}

回答1:


  1. Put the resource id of your checkbox in your row layout into the to array, corresponding to the NotesDbAdapter.KEY_CHECKED cursor in from array.

  2. Implement a SimpleCursorAdapter.ViewBinder.

  3. Have the ViewBinder.setViewValue() method check for when its called for the NotesDbAdapter.KEY_CHECKED column.

  4. When it is not the KEY_CHECKED column, have it return false the the adapter will do what it normally does.

  5. When it is the KEY_CHECKED column, have it set the CheckBox view (cast required) to checked or not as you wish and then return trueso that adapter won't attempt to bind it itself. The cursor and corresponding column id is available to access query data to determine whether to check the checkbox or not.

  6. Set your ViewBinder in your SimpleCursorAdapter via setViewBinder()

Here's one of my ViewBinder implementations. Its not for checboxes, rather its for doing some fancy formatting of a text view, but it should give you some idea for the approach:

private final SimpleCursorAdapter.ViewBinder mViewBinder =
    new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(
                final View view,
                final Cursor cursor,
                final int columnIndex) {
            final int latitudeColumnIndex =
                cursor.getColumnIndexOrThrow(
                        LocationDbAdapter.KEY_LATITUDE);
            final int addressStreet1ColumnIndex =
                cursor.getColumnIndexOrThrow(
                        LocationDbAdapter.KEY_ADDRESS_STREET1);

            if (columnIndex == latitudeColumnIndex) {

                final String text = formatCoordinates(cursor);
                ((TextView) view).setText(text);
                return true;

            } else if (columnIndex == addressStreet1ColumnIndex) {

                final String text = formatAddress(cursor);
                ((TextView) view).setText(text);
                return true;

            }

            return false;
        }
    };


来源:https://stackoverflow.com/questions/4852828/android-how-to-set-list-item-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!