是否可以在运行时更改id
组件名称?
<ImageButton android:id="@+id/ImageButton01"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" android:background="@drawable/single_square"
android:onClick="itemSelected"
/>
onClick
方法添加随机背景图像。后来,当第二次单击它时,我想知道添加了什么背景图像。为此,我想在第一次单击时将此组件的ID名称(ImageButton1)更改为已设置的图像名称(例如key_image
)。我怎么做?
如果您只想跟踪图像名称,则无需更改ID。只需在Button上使用单独的String变量,或者(可能更可取)使用setTag和getTag方法。
一个对象的标签实际上只是一个与该对象一起存储其他信息的地方。因此,在您的情况下,如果您拥有Button btn,并且想要将一个像imageName这样的字符串与其关联:
btn.setTag(imageName);
要检索字符串,请使用:
String lastImageName = (String) btn.getTag();
注意:标签可以是任何对象。它不必是String,实际上,这就是为什么我们在示例中需要将getTag结果转换为(String)的原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句