-1

我有两个图像,图像 1 和图像 2,我有 image_button,其中图像 1 作为按钮背景。现在我想要做的是,如果我按下这个 image_button,我希望图像背景变为图像 2,如果我将手指从 image_button 上移开,我希望图像 1 像以前一样再次返回.

我怎样才能做到这一点?

4

2 回答 2

0

你想要一个叫做选择器的东西。在您的可绘制文件夹中,使用以下内容创建一个 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed -->
<item android:drawable="@drawable/image1" android:state_pressed="true"/>
<!-- default -->
<item android:drawable="@drawable/image2"/>
</selector>

选择器对这类东西非常有用,你应该阅读文档

基本上,给这个东西一个名字,比如 yourSelector.xml

您可以像使用任何其他可绘制对象一样使用它,例如 @drawable/yourSelector 或 R.id.yourSelector(但请确保不要写 '.xml')

于 2013-09-05T23:24:50.490 回答
0

当点击发生时,您可以通过编程方式实现此目的:

ImageView imageIcon = (ImageView) findViewById(R.id.icon);
imageIcon.setImageResource(R.drawable.other_icon);
于 2013-09-05T22:44:08.987 回答