-1

i just read this How can I add an image on EditText and want to know if it is possible to add action on the icon when clicked...

Community
  • 1
  • 1
Mordiggian
  • 265
  • 1
  • 3
  • 11

1 Answers1

0

yes it's possible just create CustomEediTtext extends from EditText. check this solution

Create a customized EditText class CustomEditText.java:

public class CustomEditText extends EditText {
   private Drawable dRight;
   private Rect rBounds;

   public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
   }
   public CustomEditText(Context context, AttributeSet attrs) {
      super(context, attrs);
   }
   public CustomEditText(Context context) {
      super(context);
   }

   @Override
   public void setCompoundDrawables(Drawable left, Drawable top,
      Drawable right, Drawable bottom)  {
      if(right !=null)
      {
        dRight = right;
      }
      super.setCompoundDrawables(left, top, right, bottom);
   }

   @Override
   public boolean onTouchEvent(MotionEvent event) {

     if(event.getAction() == MotionEvent.ACTION_UP && dRight!=null) {
       rBounds = dRight.getBounds();
       final int x = (int)event.getX();
       final int y = (int)event.getY();

       if(x>=(this.getRight()-rBounds.width()) && x<=(this.getRight()- 
       this.getPaddingRight()) && y>=this.getPaddingTop() && y<=(this.getHeight()-
       this.getPaddingBottom())) {
         //System.out.println("touch");
         this.setText("");
         event.setAction(MotionEvent.ACTION_CANCEL);//use this to prevent the keyboard 
       }
    }
    return super.onTouchEvent(event);
  }

  @Override
  protected void finalize() throws Throwable {
     dRight = null;
     rBounds = null;
     super.finalize();
  }
}
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166