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};@Overridepublic 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};@Overridepublic 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;}}; @Overridepublic 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 數組裡存的東西是顏色矩陣,不瞭解顏色矩陣也沒關係,使用這個附件就行,只需調整亮度、對比之類的值,然後把生產的顏色矩陣複製到代碼裡。
附件:ColorMatrixDemo.swf