Question

This is a request for a best practice for handling the views in the onItemClick events in a ListView.

Each view in my ListView contains an ImageView, some TextViews, and a CheckBox wrapped in a RelativeLayout. On the item view being selected anywhere, I'd like to have the checkbox ticked/unticked as required. I would also like to have the option to change the view style i.e. so the item is highlighted by colouring the stroke.

My current issue is similar to everyone else who does this. Due to ListView recycling, if I grab the View passed into onItemClick and set the backgroundresource or checkbox checked value, it also changes them for Views that aren't currently rendered. I'd like to know the best way to achieve this goal.

I know there is a pattern to handle the CheckBox events in the ArrayAdapter directly by implementing an onClickListener, but I believe this will only respond to direct selection of the CheckBox; it will ignore any clicks on the rest of the view. Plus, if the CheckBox onClick event is fired, it will consume the click event so onItemClick won't fire, which I need to set my data.

Also, using CheckedTextView will not work since it is inside the RelativeLayout, which won't pass the checked event to the ListView. There was a post where it was recommended to create your own CheckedViewLayout that implements Checkable to handle the View checked events. If I go ahead with this, will I be able to reference my new layout class in xml, or would I then have to design each of my views again but in Java code?

If anyone else has a better solution, then please let me know.

Was it helpful?

Solution 2

In the end, I created my own CheckableRelativeLayout that implemented Checkable and used it as the main container for each ListView item. I used a Boolean value within CheckableRelativeLayout to track whether the view was clicked or not.

If required, I can post the final class.

OTHER TIPS

Hey I think this link may be useful to you,there is a details for you

Android ListView Checkbox Example - OnItemClickListener() and OnClickListener()

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