views:

164

answers:

2

Hi, I have been placing several ImageButtons programmatically in a TableLayout, every ImageButton has it's own Drawable resource as a Background. I use an XML description for the layout of the ImageButton itself and afterwards use the LayoutInflater to retrieve such an ImageButton (called genre_cell.xml):

<?xml version="1.0" encoding="utf-8"?>
<ImageButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/genreCellItemId" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="wrap_content" 
android:layout_gravity="center_horizontal"
android:paddingLeft="5dip" android:paddingRight="5dip">
</ImageButton>

And in my class I do :

myButton = (ImageButton) inflater.inflate(R.layout.genre_cell, row, false);

I have actually attached an onClickListener on every ImageButton, but now I'd like to uniquely identify which ImageButton has been clicked... I thought that maybe I could somehow retrieve the Drawable's ID used for the background and check that one with the available Drawable's int values ? Is this an option and if so how should it be implemented ? Also are there any other options ?

A: 

By chance I just came across a blog which was mentioning the setTag() and getTag() methods for the ImageButton, those I can use and thus is my question answered... Link to the blog : http://jongladwin.blogspot.com/2010/03/androidsettag-and-gettag-usage-for.html

After some looking around I even saw the setId() method and the getId() method, so it looks like there are several methologies to identify such an ImageButton... good to know :P

TiGer
A: 

Yes you can!

in your res/values folder, create an xml file button_ids.xml:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <item type="id" name="image_button_one" />
  <item type="id" name="image_button_two" />
  ...
</resources>

then after your inflate call:

myButton = (ImageButton) inflater.inflate(R.layout.genre_cell, row, false);
myButton.setId(R.id.image_button_one);
...

I haven't actually tried that, but I think this is how you're supposed to do it.

Matthias
hhmmm that means I should keep specific track of every button I have had and already have given an id ? Also the amount of buttons is NOT given, it can range betwoon 0 and probably about 80... I won't be making a resource file with 80 item's in it :PYou should immagine that setId somewhere in a loop of 80 items, so the R.id.image_button_one should dinamically change to image_button-two etc up to button_eighty...
TiGer
ah well, then it probably doesn't make much sense. If it was only a hand-full, then this would be the way to go, however.
Matthias