3

我一直在以编程方式在 TableLayout 中放置几个​​ ImageButton,每个 ImageButton 都有自己的 Drawable 资源作为背景。我对 ImageButton 本身的布局使用 XML 描述,然后使用 LayoutInflater 检索这样的 ImageButton(称为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>

在我的课堂上,我这样做:

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

我实际上在每个 ImageButton 上都附加了一个 onClickListener,但现在我想唯一标识哪个 ImageButton 已被单击...我想也许我可以以某种方式检索用于背景的 Drawable ID,并使用可用的 Drawable 进行检查整数值?这是一个选项吗?如果是,应该如何实施?还有其他选择吗?

4

2 回答 2

1

是的你可以!

在您的res/values文件夹中,创建一个 xml 文件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>

然后在你的充气电话之后:

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

我实际上没有尝试过,但我认为这就是你应该这样做的方式。

于 2010-05-04T13:39:55.653 回答
1

偶然我偶然发现了一个博客,其中提到了 ImageButton 的 setTag() 和 getTag() 方法,我可以使用这些方法,因此我的问题得到了回答……链接到博客: http://jongladwin.blogspot。 com/2010/03/androidsettag-and-gettag-usage-for.html

环顾四周后,我什至看到了 setId() 方法和 getId() 方法,所以看起来有几种方法可以识别这样的 ImageButton... 很高兴知道:P

于 2010-05-04T13:01:58.117 回答