方法一:
1,在drawable里放三幅图片,分别是获得焦点的图片、获得焦点并按下、失去焦点并按下、自然状态(也就是失去焦点,并且没有按下)。这里你准备三个照片就中。
2,在drawable文件夹下新建个imagebutton.xml文件,里面的内容为:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_focused="true"
android:state_pressed="false"
android:drawable="@drawable/snake"/>
<item
android:state_focused="true"
android:state_pressed="true"
android:drawable="@drawable/solitaire"/>
<item
android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/solitaire"/>
<item
android:drawable="@drawable/tunes"></item>
</selector>
3,在布局文件里引用这个xml文件:
<ImageButton
android:id="@+id/imgButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/image_button"/>
方法二:
imageButton.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
//更改为按下时的背景图片
v.setBackgroundResource(R.drawable.pressed);
}else if(event.getAction() == MotionEvent.ACTION_UP){
//改为抬起时的图片
v.setBackgroundResource(R.drawable.released);
}
return false;
}
});
第三种方法:
前两种方法在按键多的情况下用起来很不方便,当然不排除个别情况下就需要显示不同的图片。这里用颜色矩阵的方法,只需一张照片,就可以实现效果。且这个效果可以往任何一个ImageButton上绑定。代码如下:
/*为了使图片按钮按下和弹起状态不同,采用过滤颜色的方法.按下的时候让图片颜色变淡*/
public class MyOnTouchListener implements OnTouchListener{
public final float[] BT_SELECTED=new float[]
{ 2, 0, 0, 0, 2,
0, 2, 0, 0, 2,
0, 0, 2, 0, 2,
0, 0, 0, 1, 0 };
public final float[] BT_NOT_SELECTED=new float[]
{ 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0 };
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));
v.setBackgroundDrawable(v.getBackground());
}
else if(event.getAction() == MotionEvent.ACTION_UP){
v.getBackground().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));
v.setBackgroundDrawable(v.getBackground());
}
return false;
}
}