切换按钮图片

来源:互联网 发布:mac 邮件归类 编辑:程序博客网 时间:2024/05/22 03:06

场景

点击按钮,按钮图片发生变换;松开按钮,图片还原。

方法一

增加触摸监听

ImageButton btn = (ImageButton)findViewById(R.id.xxx);        btn.setOnTouchListener(new View.OnTouchListener(){                public boolean onTouch(View v, MotionEvent event) {                            if(event.getAction() == MotionEvent.ACTION_DOWN){                    // 设置点击时按钮图片   ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.xxx));                                        }else if(event.getAction() == MotionEvent.ACTION_UP){                    // 还原图片    ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.xxx));               }            return false;         }     });

方法二

配置XML文件

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/scan_select" android:state_pressed="true" />    <item android:drawable="@drawable/scan_normal" /></selector>
<TextView    android:id="@+id/tvScan"    android:layout_width="0dp"    android:layout_height="wrap_content"    android:layout_weight="1"    android:drawablePadding="@dimen/d6"    android:drawableTop="@drawable/scan_select"    android:gravity="center"    android:text="@string/scan"    android:textColor="@color/color_dedede"    android:textSize="@dimen/s15" />