简体   繁体   English

检测自定义ListView布局中复选框的单击?

[英]Detect click on checkbox in custom ListView layout?

I know there's tons of other threads around about this same topic, but none of them seem to work with my scenario and I couldn't get my listview to work with their code. 我知道围绕同一主题还有很多其他线程,但是它们似乎都不适合我的方案,并且我无法让listview与它们的代码一起使用。 Basically, I'm using a SimpleCursorAdapter to populate a listview with items from the database. 基本上,我正在使用SimpleCursorAdapter用数据库中的项目填充列表视图。 Each listview row uses a custom layout which consists of a checkbox and a line of simple text. 每个列表视图行使用一个自定义布局,该布局由一个复选框和一行简单文本组成。 How do I detect a click on the checkbox? 如何检测对复选框的单击? I know I need to use OnItemClickListener, but I don't know how to incorporate that into my code. 我知道我需要使用OnItemClickListener,但是我不知道如何将其合并到我的代码中。 Here's my code: 这是我的代码:

remindersCursorAdapter = new SimpleCursorAdapter(this,
                         R.xml.view_reminders_item_layout,
                         remindersCursor, new String [] { RemindersDAO.NAME },
                         new int[] { R.id.view_reminders_item_text } );

viewRemindersListView.setAdapter(remindersCursorAdapter);

R.xml.view_reminders_item_layout is the custom listview layout file. R.xml.view_reminders_item_layout是自定义列表视图布局文件。 How do I capture the checkbox from this file and set a click listener to it? 如何从此文件捕获复选框并为其设置点击侦听器? Thanks for all your help! 感谢你的帮助!

If you want to check the checkbox when a item is clicked, you can do it by setting checked status of Checkbox in onItemClick method. 如果要在单击项目时选中复选框,则可以通过在onItemClick方法中设置Checkbox的选中状态来做到这一点。

  @Override
  public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

       // now get the checkbox view. Then set the checked status.
        CheckBox checkbox = (CheckBox) view.findViewById(R.id.check_box);
        checkBox.setChecked(!checkbox.isChecked());
  }

If you want to detect the click on only checkbox then set the focusable true in xml. 如果要检测仅单击复选框,则在xml中设置focusable true。 // in your custom list view item. //在自定义列表视图项。 It takes the current view focus. 它需要当前的视图焦点。

      <Checkbox>
          android:focusable="true"
      </Checkbox>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM