Magic
Magic

Reputation: 1196

Assign bundle or argument to ImageView in Android

My Android app has a listview of avatar(ImageView).
I want the ImageView clickable. And I need to distinguish which ImageView the user click and pass some argument then need to retrieve it in OnClick.
How I can retrieve the info(by bundle or any other argument) in OnClick method?

ImageView avatar = new ImageView();
// I want to pass some argument to avatar, then retrieve in OnClick
avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i("Avatar onClick", "Entered onClick method");
                    // Here I want to retrieve the argument passing to ImageView before. 
                }
            }); 

Upvotes: 0

Views: 95

Answers (3)

LinaInverce
LinaInverce

Reputation: 186

In my opinion, We can use a class object which contains the path of the imageview and the index of the imageview. such as

public class ForumReplyItem {
 private int id;
 private String path
}

then your listview data source should be "ArrayList < ForumReplyItem > myReplys"

In your adapter class, you can use

final ForumReplyItem temp = myReplys.get(position);

to know the index of the item you want to click.then you can init your imageview with the value path and know which imageview you are clicking by value id.We can use setOnClickListener at last in this way.I hope this will be helpful.

Upvotes: 0

jomartigcal
jomartigcal

Reputation: 813

You can setTag to pass data to the Imageview. Then, you can cast the "View v" parameter of public void onClick(View v) {..} into an ImageView and use getTag from the imageView.

ImageView avatar = new ImageView();
//setTag to imageview
avatar.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         ImageView image = (ImageView) v;
         //getTag from image
         //TODO action
     }
});

Upvotes: 0

CodeMonster
CodeMonster

Reputation: 300

In my way,

  • You should hold the data in a object(this object represent for the
    row). Then use listview.setOnItemClickListener();

  • Or You can hold data by imageView.setTag();

Upvotes: 2

Related Questions