Reputation: 742
I have made a custom listView for my android app, and I have a problem creating separate onClickListeners for separate parts of the item. My item has a picture and a text. What I want is to start different activities depending on which of those has been clicked.
That onClick() method shoud start an activity which makes it impossible to define in getView() method of my DataBinder class. (DataBinder infalates my listView with custom layout)
Any help?
Thank you!
Upvotes: 5
Views: 8111
Reputation: 635
One option would be to include an onClick method for the separate elements. Assuming that you've built the custom row in XML, it's simple to add a method in the onClick field, set that element (say, an image) to allow clicks (if it isn't already) and define the method in your class. Then, if the row gets clicked, the listview click handler fires, but if the element gets clicked (the image) then it's own onClick method gets fired.
Upvotes: 0
Reputation: 7371
In your custom ListAdapter's
getView
method you should add onClickListeners
to the different sub-views you want to act to clicks.
An example on how to implement the getView
method:
class CustomListAdapter extends ArrayAdapter<String> implements OnClickListener {
public CustomListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setOnClickListener(this);
ImageView iv = (ImageView) v.findViewById(R.id.imageView1);
iv.setOnClickListener(this);
return super.getView(position, convertView, parent);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.textView1:
// Do stuff accordingly...
break;
case R.id.imageView1:
// Do stuff when imageView1 is clicked...
default:
break;
}
}
}
Upvotes: 9
Reputation: 12656
It is not impossible to define separate onClick()
methods for the ImageView
and the TextView
in your list item. This is exactly what you have to do instead of using the onClick()
handler for your ListView
.
Implement onClick()
methods in your adapter's getView()
for each item.
Upvotes: 1