0

I have a customized list item with 2 Buttons ( save , share) in a ListView.

How to get which Button is clicked in list item in onItemClick() method ?

Like:

      ListView
----------------------------
[Text]
[SAVE BUTTON1][SHARE BUTTON2]
-----------------------------
[Text]
[SAVE BUTTON1][SHARE BUTTON2]
-----------------------------
[Text]
[SAVE BUTTON1][SHARE BUTTON2]
-----------------------------
-
-
Md Rahman
  • 1,812
  • 1
  • 14
  • 15
ida
  • 545
  • 2
  • 5
  • 20

2 Answers2

2

You can do the following,

set Tag to your Button in the getView() method of your ListView

btn.setTag(position);

then set OnClickListener to your button,

btn.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        Toast.makeText(getApplicationContext(), "button position is: "+v.getTag(),
   Toast.LENGTH_LONG).show();
    }
});
Spring Breaker
  • 8,233
  • 3
  • 36
  • 60
1

For custom adapters you should use View.OnClickListener and set it to each individual element Button using setOnClickListener() method.

the onItemClick() is part of OnItemClickListener that only responds to click on the whole view. This is usually used for simpler lists using one of the default adapters.

Budius
  • 39,391
  • 16
  • 102
  • 144
  • If i use setOnClickListener(), how to get the data associated with the list item in Listener function. – ida Apr 24 '14 at 03:35
  • every `View` in Android have methods `setTag(Object)` and `getTag()`. Those can be used to store any object you want. So let's say your adapter is an `ArrayAdapter` you can store each individual book inside the view itself. That way during `onClick(View v)` you can `Book b = (Book) v.getTag();` – Budius Apr 24 '14 at 08:04
  • I am using the 'SimpleCursorAdaptor' , directly from sqlite fetching the data and providing it as adaptor for the list view. How to set the object, as data us coming from the database directly.. – ida Apr 24 '14 at 08:25
  • The method is still the same. For example, if you need an ID to save, you can put the String with the ID in the tag. If you need more than that, you can use a `HashMap` to put all the values you need, or create a Class just to hold those values. – Budius Apr 24 '14 at 09:08
  • followed the [source](http://thinkandroid.wordpress.com/2010/01/11/custom-cursoradapters/) – ida Apr 25 '14 at 19:00