我有图像按钮,我想在我点击它时更改图像

时间:2013-09-05 22:37:12

标签: android

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

我该怎么做?

2 个答案:

答案 0 :(得分:0)

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

ImageView imageIcon = (ImageView) findViewById(R.id.icon);
imageIcon.setImageResource(R.drawable.other_icon);

答案 1 :(得分:0)

你想要一个叫做选择器的东西。在drawable文件夹中,使用以下内容创建一个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一样使用它,比如@ drawable / yourSelector或R.id.yourSelector(尽管不要写'.xml')

相关问题