带有Button的Android Edittext如何对按钮执行操作

时间:2012-07-08 04:49:29

标签: android search button android-edittext

我刚读过这个How can I add an image on EditText,想知道点击后是否可以在图标上添加操作...

1 个答案:

答案 0 :(得分:0)

是的,可以从CustomEediTtext扩展EditText。检查此解决方案

创建一个自定义的EditText类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();
  }
}