开发者

Android: How to set List item checked?

开发者 https://www.devze.com 2023-02-07 13:11 出处:网络
I have an android.R.layout.simple_list_item_multiple_choice with checkboxes an want so initiate some of them.

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() {
    Curs开发者_StackOverflow中文版or 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. 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;
        }
    };
0

精彩评论

暂无评论...
验证码 换一张
取 消