[英]How to make checkbox checked in the OnItemClickListener()?
I have a checkbox in my ListView row which looks like this. 我的ListView行中有一个复选框,如下所示。
===========================================
[CheckBox] [TextView] [TextView] [TextView]
===========================================
the xml code is here xml代码在这里
<CheckBox
android:id="@+id/course_search_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:clickable="false"
android:focusable="false" />
And I have already made the checkbox not clickable and focusable so that the click event will be passed to the ListView. 而且我已经使复选框不可点击和可聚焦,以便将click事件传递给ListView。
What I want to do here is that when the user click the listview, make the CheckBox checked and add the clicked position of listview to an arraylist. 我想要做的是当用户单击列表视图时,选中CheckBox并将listview的单击位置添加到arraylist。 So how can I make the CheckBox checked in an OnItemClickListener of ListView?
那么如何在ListView的OnItemClickListener中检查CheckBox?
Help please, thanks. 请帮助,谢谢。
You could add this code within your OnItemClickListener
: 您可以在
OnItemClickListener
添加此代码:
public void onItemClick(AdapterView parent, View view, int position, long id){
CheckBox box = (CheckBox)view.findViewById(R.id.course_search_checkbox);
box.setChecked(true);
}
Well if it is a single selection list then you need these apis from ListView
to get position/id: 好吧,如果它是一个单一的选择列表,那么你需要从
ListView
获取这些api来获得位置/ id:
getSelectedItemId()
getSelectedItemPosition()
And now if you have implemented your Adapter for ListView. 现在,如果您已经为ListView实现了适配器。 In there for apis like
bindView
, getView
etc (depending upon which adapter you have used), you have set the checked state on based on the above apis. 在那里为apis,如
bindView
, getView
等(取决于你使用的适配器),你已经根据上面的apis设置了检查状态。 Something like 就像是
public View getView(int position, View convertView, ViewGroup parent)
{
ListView listView = (ListView)parent; // This is the parent view group passed as argument.
CheckBox cb = (CheckBox)convertView.findViewById(R.id.check_box);
if(getSelectedItemPosition() == position)
cb.setChecked(true);
else
cb.setChecked(true);
}
For Multiselection you need below apis from ListView: 对于Multiselection,您需要从ListView下面的apis:
getCheckedItemPositions
The code for checking the check box will be similar to single selection (not exact though). 用于选中复选框的代码将类似于单个选择(尽管不是很精确)。
NOTE: Code mentioned is just for reference. 注意:提到的代码仅供参考。 It is not an optimized code.
它不是优化的代码。 Definitely need modifications.
绝对需要修改。 NOTE:
注意:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.