【问题标题】:Android: How to set List item checked?Android:如何设置列表项选中?
【发布时间】:2011-06-18 16:17:11
【问题描述】:

我有一个带有复选框的 android.R.layout.simple_list_item_multiple_choice 想要启动其中的一些。 我怎样才能做到这一点? 我有以下代码:

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

}

【问题讨论】:

标签: android list checkbox adapter


【解决方案1】:
  1. 将行布局中复选框的资源ID放入to数组中,对应from数组中的NotesDbAdapter.KEY_CHECKED光标。

  2. 实现SimpleCursorAdapter.ViewBinder

  3. ViewBinder.setViewValue() 方法检查何时调用NotesDbAdapter.KEY_CHECKED 列。

  4. 当它不是 KEY_CHECKED 列时,让它返回false 适配器会做它通常做的事情。

  5. 当它是 KEY_CHECKED 列时,让它根据需要将 CheckBox 视图(需要强制转换)设置为选中或不选中,然后返回 true,这样适配器就不会尝试自行绑定它。游标和对应的列id可用于访问查询数据以确定是否选中复选框。

  6. 通过setViewBinder()在 SimpleCursorAdapter 中设置 ViewBinder

这是我的 ViewBinder 实现之一。它不是用于复选框,而是用于对文本视图进行一些花哨的格式化,但它应该为您提供一些方法的想法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    相关资源
    最近更新 更多