1

I am using simple_list_item_multiple_choice with list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); to create a list of check boxes populated from a database query. I am then using onListItemClick to handle the clicking of the list, again that is working fine. What I can find no way of doing (after 5 days) is writing an if statement based on whether or not the check box attached to the list item is checked. What I need is the equivalent of the example below which works perfectly for a check box where I can use the android:onClick element to fire the method below.

public void onCheckboxClicked(View v) {
        // Perform action on clicks, depending on whether it's now checked
        if (((CheckBox) v).isChecked()) {
            Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Not selected", Toast.LENGTH_SHORT).show();
        }
    }

This is critical to my app so any advice would be greatly appreciated. Below is the simpleCusrorAdapter is am using:

 Cursor cursor3 = db.rawQuery("SELECT _id, symname FROM tblsymptoms WHERE _id IN ("+sympresult+") ", null);

        adapter = new SimpleCursorAdapter(
                this, 
                android.R.layout.simple_list_item_multiple_choice,
                cursor3, 
                new String[] {"symname","_id"}, 
                new int[] {android.R.id.text1});
        setListAdapter(adapter);
        ListView list=getListView();
        list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
4

2 回答 2

3

在找到这个非常有用的博客项目后我已经解决了这个问题

我将我的 onListItemClick 更改为以下内容,它就像一个梦一样工作:

public void onListItemClick(ListView parent, View view, int position, long id) {


      CheckedTextView check = (CheckedTextView)view;
      check.setChecked(!check.isChecked());
      boolean click = !check.isChecked();
      check.setChecked(click);
      if (click) {
            Toast.makeText(this, "Not Selected", Toast.LENGTH_SHORT).show();
      } else {
          Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
      } 
}
于 2012-03-17T19:15:28.603 回答
0

如果我理解正确,您列表中的每一行都有一个复选框。When an item in the list is selected you want to be able to tell if the corresponding checkbox is checked?

尝试对每个列表项 View 对象使用 setTag(...) 方法。然后,当调用 onListItemClick() 方法时,您可以在视图上调用 getTag(...) (这将返回您的复选框)。我假设您正在使用自定义适配器来填充列表。填充时要调用:

   setTag( CHECKBOX_KEY, checkbox );

例如:

protected void onListItemClick(ListView l, View v, int position, long id) {
    CheckBox cb = (CheckBox)v.getTag( CHECKBOX_KEY );

    boolean isChecked = false;

    if( null != cb ) {
        isChecked = cb.isChecked();
    }

    // .. do whatever you have to here...    

}

希望这可以帮助...

于 2012-03-17T00:59:17.937 回答