Question

I have a checkbox in my ListView row which looks like this.

===========================================
[CheckBox] [TextView] [TextView] [TextView]
===========================================

the xml code is here

<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.

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. So how can I make the CheckBox checked in an OnItemClickListener of ListView?

Help please, thanks.

Was it helpful?

Solution

You could add this code within your 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);
}

OTHER TIPS

Well if it is a single selection list then you need these apis from ListView to get position/id:

getSelectedItemId()
getSelectedItemPosition()

And now if you have implemented your Adapter for 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. 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:

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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top