Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniquely Identify ImageButtons placed Programmatically

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 ?

like image 578
TiGer Avatar asked Jun 16 '26 15:06

TiGer


1 Answers

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.

like image 110
Matthias Avatar answered Jun 18 '26 05:06

Matthias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!