SoFunction
Updated on 2025-04-06

Share the code implementation method of Android ImageButton custom button press effect


/** 
* Press this button to perform color filtering
   */ 
  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 };  

  /** 
* The button restores the original color filter
   */ 
  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) {  
    ().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));  
    (());  
   }  
   else 
   {  
    ().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));  
     (());  
   }  
  }  
 };  

  /** 
* Button touch press effect
   */ 
 public final static OnTouchListener buttonOnTouchListener=new OnTouchListener() {  
  @Override 
  public boolean onTouch(View v, MotionEvent event) {  
   if(() == MotionEvent.ACTION_DOWN){  
    ().setColorFilter(new ColorMatrixColorFilter(BT_SELECTED));  
    (());  
    }  
    else if(() == MotionEvent.ACTION_UP){  
     ().setColorFilter(new ColorMatrixColorFilter(BT_NOT_SELECTED));  
     (());  
    }  
   return false;  
  }  
 };  

 /** 
* Set the picture button to get the focus change status
  * @param inImageButton 
  */ 
 public final static void setButtonFocusChanged(View inView)  
 {  
  (buttonOnTouchListener);  
  (buttonOnFocusChangeListener);  
 }