简体   繁体   中英

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!

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM