转载地址:http://www.cnblogs.com/xiaowenji/archive/2011/02/04/1949165.html
Android中使用ImageButton的话,程序里按下那个ImageButton时感觉不到任何按下的效果。
网上有2中经典的解决方案,一种是使用xml,一种是写在代码里。
这里我想要介绍另一种方法,使ImageButton有按下的特效,只需要准备一张普通的图片,不需要按下效果的图片。
直接看示例代码,创建 TouchLight 和 TouchDark 这两个 OnTouchListener,然后给 ImageButton 设置OnTouchListener就行了,如果使用TouchLight,则按下效果是按键变亮;另一个就是变暗。
import android.app.Activity;
import android.graphics.ColorMatrixColorFilter;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class TouchedAnimation extends Activity {
public static final OnTouchListener TouchLight = new OnTouchListener() {
public final float[] BT_SELECTED = new float[] {1,0,0,0,50,0,1,0,0,50,0,0,1,0,50,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};
@Override
public boolean onTouch(View v, MotionEvent event) {
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;
}
};
public static final OnTouchListener TouchDark = new OnTouchListener() {
public final float[] BT_SELECTED = new float[] {1,0,0,0,-50,0,1,0,0,-50,0,0,1,0,-50,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};
@Override
public boolean onTouch(View v, MotionEvent event) {
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;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton ib1, ib2;
ib1 = (ImageButton) findViewById(R.id.ImageButton01);
ib2 = (ImageButton) findViewById(R.id.ImageButton02);
ib1.setOnTouchListener(TouchLight);
ib2.setOnTouchListener(TouchDark);
}
}
代码里的两个 float 数组里存的东西是颜色矩阵,不了解颜色矩阵也没关系,使用这个附件就行,只需调整亮度、对比度之类的值,然后把生产的颜色矩阵复制到代码里。