Home > other >  Check which ImageView was clicked inside ListView
Check which ImageView was clicked inside ListView

Time:10-28

I have a ListView which works with Custom-Item-Templates.

Inside the List-Item Template are ImageViews (used as Buttons) and several Strings. The Data is bound with CustomAdapter.

I want to to do specific things inside the ListView with each Item on clicking different ImageViews.

I come from .NET and WebDevelopment and very new in Android.

How can I achieve to check which Button or Image in which ListItem was clicked.

Normally i would give each element in ListItem custom attribute whith unique_id including a key from the DataItem and get that Key in a Click-Event of Buttom and so on.

Is there any opinion to give a ImageView a Custom Attribute like 'MyCustomID' and get that in the Click-Event from it? Or how is the usual workflow for a situation like this: ListItems with repeating Elements and checking what ListItem belongs to the clicked Element inside.

Please help!

CodePudding user response:

Try with this

listView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   //  position is the index of clicked item.
   
}

});

CodePudding user response:

First of all, I'd recommend to change to RecyclerView. It is more performant, flexible and easier to use. Here you can check how to do it.

About your question: I don't remember exactly how to implement ListView, but I believe that you have an adapter. In that adapter, you are creating the view of your items. So, what you can do is create a listener interface that receives the info of your items. Something like:

interface OnImageItemClickListener {
    fun onImageClicked(imageInfo: ImageInfo)
}

data class ImageInfo(
    val id: Long,
    val uri: URI,
)

Then you can pass an implementation of that interface to your adapter, and then use it in the View.setOnClickListener method:

class CustomAdapter(
    private val listener: OnImageItemClickListener,
    private val info: List<ImageInfo>,
) : ... {
    override getView(position: Int, convertView: View, parent: ViewGroup): View {
        // Inflate your view...
        view.setOnClickListener {
            listener.onImageClicked(info[position])
        }
    }
}

Again, I highly recommend to migrate to RecyclerView. If you implement it, you'll have to follow the same steps.

  • Related