如何在列表视图行中收听复选框?

时间:2011-10-03 19:36:04

标签: android listview checkbox listener

String[] from = new String[] { CallrzDbAdapter.C_NAME,CallrzDbAdapter.C_EMAIL,CallrzDbAdapter.C_PHONE };
    int[] to = new int[] {R.id.cName, R.id.cEmail, R.id.cPhone };


    notes = new SimpleCursorAdapter(this,
            R.layout.row, cursor, from, to);

    ListView view =getListView();
    view.setHeaderDividersEnabled(true);
    view.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    view.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view,
                int position, long arg3) {
            Toast.makeText(getApplicationContext(), "Hello"+position+" is clicked ",
                      Toast.LENGTH_SHORT).show();

            return false;
        }
      });

    //setListAdapter(notes);
    setListAdapter(notes);

我有一个列表行的自定义布局,也有一个复选框。如何为复选框事件创建监听器?我搜索并听说过bindView但有没有人可以更清楚地解释一下? this是有人解释的链接,但我无法将其插入我的代码中。

3 个答案:

答案 0 :(得分:0)

您可以创建自己的ViewBinder,在setViewValue中只需执行以下操作:

 class MyViewBinder implements SimpleAdapter.ViewBinder {
  public boolean setViewValue(View view, Object data, String textRepresentation) {
   int id = view.getId();
   /* handle this particular item from our own view
   if (id == R.id.myViewId) {
    ((CheckBox) view).setOnItemLongClickListener(...);
    ((CheckBox) view).setText(...);
    return true;
   }
   return false;
  }
 }

然后,您可以使用SampleAdapter获取数据并调用

adapter.setViewBinder(new MyViewBinder());

答案 1 :(得分:0)

来自view的{​​{1}}应该包含您的复选框。

您可以像往常一样进行检索:

onItemLongClick

如果我错了,请纠正我,我通常使用自定义Checkbox yourCheckbox = (Checkbox) view.findViewById(R.id.your_checkbox_id);

编辑:

你可以看一下这个例子。 Android Series: Custom ListView items and adapters 提示:示例中的ArrayAdapter可以getView findViewById

答案 2 :(得分:0)

以下是答案在阅读 link 后,我发现了这一点。它非常清楚地解释了它。谢谢大家。