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?
The Attr interface represents an attribute in an Element object.
Create an XML res/values/attrs. xml file to define new attributes alongwith their data type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With