Android中使用ImageButton的话,程序里按下那个ImageButton时感觉不到任何按下的效果。
网上有2中经典的解决方案,一种是使用xml,一种是写在代码里。
这里我想要介绍另一种方法,使ImageButton有按下的特效,只需要准备一张普通的图片,不需要按下效果的图片。
直接看示例代码,创建 TouchLight 和 TouchDark 这两个 OnTouchListener,然后给 ImageButton 设置OnTouchListener就行了,如果使用TouchLight,则按下效果是按键变亮;另一个就是变暗。
01 |
import android.app.Activity; |
02 |
import android.graphics.ColorMatrixColorFilter; |
03 |
import android.view.MotionEvent; |
04 |
import android.view.View; |
05 |
import android.view.View.OnTouchListener; |
07 |
public class TouchedAnimation extends Activity
{ |
09 |
public static final OnTouchListener
TouchLight = new OnTouchListener() { |
11 |
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 }; |
12 |
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 }; |
15 |
public boolean onTouch(View
v, MotionEvent event) { |
16 |
if (event.getAction() == MotionEvent.ACTION_DOWN) { |
17 |
v.getBackground().setColorFilter( |
18 |
new ColorMatrixColorFilter(BT_SELECTED)); |
19 |
v.setBackgroundDrawable(v.getBackground()); |
20 |
} else if (event.getAction()
== MotionEvent.ACTION_UP) { |
21 |
v.getBackground().setColorFilter( |
22 |
new ColorMatrixColorFilter(BT_NOT_SELECTED)); |
23 |
v.setBackgroundDrawable(v.getBackground()); |
29 |
public static final OnTouchListener
TouchDark = new OnTouchListener() { |
31 |
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 }; |
32 |
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 }; |
35 |
public boolean onTouch(View
v, MotionEvent event) { |
36 |
if (event.getAction() == MotionEvent.ACTION_DOWN) { |
37 |
v.getBackground().setColorFilter( |
38 |
new ColorMatrixColorFilter(BT_SELECTED)); |
39 |
v.setBackgroundDrawable(v.getBackground()); |
40 |
} else if (event.getAction()
== MotionEvent.ACTION_UP) { |
41 |
v.getBackground().setColorFilter( |
42 |
new ColorMatrixColorFilter(BT_NOT_SELECTED)); |
43 |
v.setBackgroundDrawable(v.getBackground()); |
50 |
public void onCreate(Bundle
savedInstanceState) { |
51 |
super .onCreate(savedInstanceState); |
52 |
setContentView(R.layout.main); |
55 |
ib1 = (ImageButton) findViewById(R.id.ImageButton01); |
56 |
ib2 = (ImageButton) findViewById(R.id.ImageButton02); |
58 |
ib1.setOnTouchListener(TouchLight); |
59 |
ib2.setOnTouchListener(TouchDark); |
代码里的两个 float 数组里存的东西是颜色矩阵,不了解颜色矩阵也没关系,使用这个附件就行,只需调整亮度、对比度之类的值,然后把生产的颜色矩阵复制到代码里。