When you use a Button, there are two ways to achieve the "Press" effect:
1. In the code.
ImageButton. setOnTouchListener (new OnTouchListener () {@ Override public boolean onTouch (View v, MotionEvent event) {if (event. getAction () = MotionEvent. ACTION_DOWN) {// change to the background image v. setBackgroundResource (R. drawable. pressed);} else if (event. getAction () = MotionEvent. ACTION_UP) {// change to the image v. setBackgroundResource (R. drawable. released) ;}return false ;}});
2. Use an XML file.
This file is placed under the drawable directory. Name it button_add_x.xml
When using
I found that this implementation process is universal, but it is very troublesome. A single button requires multiple images or even a layout...
What if a game has hundreds of buttons?
The following code was developed:
/*** Press this button to filter colors */public final static 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 }; /*** Color Filter for button restore to original state */public final static 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 }; /*** button focus change */public final static OnFocusChangeListener buttonOnFocusChangeListener = new OnFocusChangeListener () {@ Override public void onFocusChange (View v, boolean hasFocus) {if (hasFocus) {v. getBackground (). setColorFilter (new ColorMatrixColorFilter (BT_SELECTED); v. setBackgroundDrawable (v. getBackground ();} else {v. getBackground (). setColorFilter (new ColorMatrixColorFilter (BT_NOT_SELECTED); v. setBackgroundDrawable (v. getBackground () ;}};/*** click to touch and press the button */public final static OnTouchListener buttonOnTouchListener = new OnTouchListener () {@ Override public boolean onTouch (View v, motionEvent) {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 ;};/*** set the image button to get the focus change status * @ param inImageButton */public final static void setButtonFocusChanged (View inView) {inView. setOnTouchListener (buttonOnTouchListener); inView. setOnFocusChangeListener (buttonOnFocusChangeListener );}
Call Method
Public final static void setButtonFocusChanged (View inView)
You can.
Principle]
Use the setColorFilter method of the Drawable class to filter the color offset of the image.