Android中使用ImageButton的話,程序裡按下那個ImageButton時感覺不到任何按下的效果。
網上有2中經典的解決方案,一種是使用xml,一種是寫在代碼裡。
這裡我想要介紹另一種方法,使ImageButton有按下的特效,只需要準備一張普通的圖片,不需要按下效果的圖片。
直接看示例代碼,創建 TouchLight 和 TouchDark 這兩個 OnTouchListener,然後給 ImageButton 設置OnTouchListener就行了,如果使用TouchLight,則按下效果是按鍵變亮;另一個就是變暗。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | 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 數組裡存的東西是顏色矩陣,不瞭解顏色矩陣也沒關係,使用這個附件就行,只需調整亮度、對比度之類的值,然後把生產的顏色矩陣複製到代碼裡。