Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom data / attributes to button in Android

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?

like image 996
Eduard Luca Avatar asked Jan 26 '13 16:01

Eduard Luca


People also ask

What is attr file in Android?

The Attr interface represents an attribute in an Element object.

What is the name of the file which is used to declare custom attributes?

Create an XML res/values/attrs. xml file to define new attributes alongwith their data type.


1 Answers

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.

like image 74
user Avatar answered Oct 07 '22 12:10

user