Add custom data / attributes to button in Android

Eduard Luca picture Eduard Luca · Jan 26, 2013 · Viewed 7.4k times · Source

What I am doing right now is to pull some data from an API and for each item in the response, I inflate the layout and add another item to the layout.

What I want is to have an "add to favorites" button, which will add the current item in an SQLite database. I've already created the DAO stuff and the DB handling, but there's one thing that bugs me.

When I click the button, I can't tell which item ID's button has been clicked. I'm normally a web developer and on the web, a button can have data-xxx="yyy" attributes, where xxx and yyy are what ever the developer wants.

Is this possible in Android? I have another solution, but it's more like a "hack": create a hidden TextView that holds my item's ID, and get the onClick event to check that TextView (the one that is a sibling to the button). Any other ideas?

Answer

user picture user · Jan 26, 2013

When I click the button, I can't tell which item ID's button has been clicked

You can add a piece of arbitrary data to any View by using the setTag() method. When you inflate the layout for a new item, get the id of that item and set it as the tag for the Button in the newly inflated layout corresponding to that item. You'll be able then, in the OnClickListener for the Button, to retrieve the tag(the id in your case) with the getTag() method and happily insert it in the database.