kevin
kevin

Reputation: 827

How to make checkbox checked in the OnItemClickListener()?

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.

Upvotes: 4

Views: 5910

Answers (2)

havexz
havexz

Reputation: 9590

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:

Upvotes: 0

Chris
Chris

Reputation: 23179

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);
}

Upvotes: 6

Related Questions