我想制作图像按钮,所以当它按下时,我会将未按下的图像替换为按钮的按下图像,然后转到其他 Activity 。我在 drawable 中有两个不同的图像。
我有两个 xml 文件:
第一个-加载主要 Activity :背景和图像按钮
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/black"
android:orientation="vertical" >
<ImageButton
android:id="@+id/b1_l"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/s1"
android:scaleType="centerCrop"
android:background="@color/trans"
android:src="@drawable/b1_l" />
</RelativeLayout>
第二个:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false"
android:drawable="@drawable/image_not_pressed" />
<item android:state_pressed="true"
android:drawable="@drawable/image_pressed"" />
</selector>
除了我的 xml 之外,我还需要编写什么代码? 还是我可以传递 xml 并将其仅作为代码编写...?
谢谢!
最佳答案
您通常需要为按下和默认(未按下)状态绘制可绘制对象。为此,您可以拥有像这样(如下)的 xml 文件。您需要将此 xml 文件放在 drawable 文件夹中,然后用作 ImageButton 的 src 或 Button 的背景源。
让它命名为 mybutton.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/your image name" />
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/your image name" />
<item android:drawable="@drawable/your image name" />
</selector>
主要 Activity 的布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/black"
android:orientation="vertical" >
<ImageButton
android:id="@+id/b1_l"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/s1"
android:scaleType="centerCrop"
android:background="@color/trans"
android:src="@drawable/mybutton" />
</RelativeLayout>
关于android - 按下时使图像按钮发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12446135/