实现自定义列表视图的复选框

时间:2012-10-26 08:33:56

标签: android database listview checkbox

我编写了代码来从数据库中获取值并将这些值绑定到listview。因为我现在根据需要使用了自定义列表视图我想要列表中每个项目的复选框。如何做到这一点

image=(ImageView)findViewById(R.id.image);
        note=(ImageButton)findViewById(R.id.note);
        tick=(ImageButton)findViewById(R.id.tick);
        cross=(ImageButton)findViewById(R.id.cross);
        Intent intent = getIntent();
        Bitmap photo = (Bitmap) intent.getParcelableExtra("photooo");
        image.setImageBitmap(photo);
        if(photo!=null)
        {
            dbHelper = new RecordsDbAdapter(this);
            dbHelper.open();
            displayListView();
        }

    }
    private void displayListView() {
        Cursor cursor = dbHelper.fetchAllRecords();
        String[] columns = new String[] {
                RecordsDbAdapter.KEY_NAME,
                RecordsDbAdapter.KEY_BIRTHDAY,

        };
        int[] to = new int[] {
                R.id.name,
                R.id.birthdate,
        };
        dataAdapter = new SimpleCursorAdapter(
                this, R.layout.row,
                cursor,
                columns,
                to);
        ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(dataAdapter);
    }
}

2 个答案:

答案 0 :(得分:5)

  • 使用LayoutInflater add复选框列出视图
  • 使用SetTag方法后,将Tagvalue添加到复选框
  • 此标记值在listview中的每个项目中单独复选框 下面的代码示例:`

LayoutInflater inflater = getLayoutInflater();

 convertView = inflater.inflate(R.layout.home1, null);

ViewHolder holder1 = new ViewHolder(); holder1.text =(TextView)convertView.findViewById(R.id.textView1);

   holder1.ch=(CheckBox)convertView.findViewById(R.id.checkBox1);
  holder1.ch .setTag(position);

答案 1 :(得分:1)

就像你在转到R.layout.row的XML文件之前所做的那样,并输入以下代码:

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:text="checkbox" />

然后像这样编辑你的代码: -

    private void displayListView() {
    Cursor cursor = dbHelper.fetchAllRecords();
    String[] columns = new String[] {
            RecordsDbAdapter.KEY_NAME,
            RecordsDbAdapter.KEY_BIRTHDAY,
            RecordsDbAdapter.KEY_CHECKBOX

    };
    int[] to = new int[] {
            R.id.name,
            R.id.birthdate,
            R.id.checkbox
    };
    dataAdapter = new SimpleCursorAdapter(
            this, R.layout.row,
            cursor,
            columns,
            to);
    ListView listView = (ListView) findViewById(R.id.list);
    listView.setAdapter(dataAdapter);
}