Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set onClickListener for separate parts of custom listView item? [Android]

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!

like image 774
Nikola Milutinovic Avatar asked Apr 02 '13 16:04

Nikola Milutinovic


1 Answers

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;
        }
    }
}
like image 200
Darwind Avatar answered Sep 19 '22 17:09

Darwind