Button按钮图片切换效果设置。

通常在工程中用到图片按钮点击事件,大多都用ImageButton。在这里我们用

Button的点击事件,在图片的切换过程中不再通过setBackgroundResource()设置

点击效果。而是通过.xml预先设置好切换效果。在这里我们习惯把该.xml文件放到drawable文件夹下。

代码如下:


//xml文件 名称这里为test_press.xml

1、 android:state_pressed="true" 为点击后效果

2、 android:state_focused="true"

3、 最后一行 <item android:drawable="@drawable/ok"/>

是必不可少的,否则会引起布局混乱。另外该行的drawable其实就是

默认的显示图片。所以有了该行代码,上面的2可以不用写了。为了程序的

完整性,我们建议还是要写上啦。

<?xmlversion="1.0"encoding="utf-8"?><selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:drawable="@drawable/ok_press"android:state_pressed="true"/><itemandroid:drawable="@drawable/ok"android:state_focused="true"/><itemandroid:drawable="@drawable/ok"/></selector>


//Button按钮的设置

只需设置一步即可

android:background="@drawable/test_press"

<Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/test_press"/>


在主代码中只需要正常使用Button的监听器即可,至于点击效果则会自动切换。