Manejar eventos de clic en un dibujo dentro de un EditText

He agregado una imagen a la derecha del texto en un widget EditText , usando el siguiente XML:

  

Pero quiero borrar EditText cuando se hace clic en la imagen incrustada. ¿Cómo puedo hacer esto?

En realidad, no necesitas extender ninguna clase. Digamos que tengo EditComment editComment con drawableRight

  editComment.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_LEFT = 0; final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (editComment.getRight() - editComment.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { // your action here return true; } } return false; } }); 

obtenemosRawX getRawX() porque queremos obtener la posición real del tacto en la pantalla, no relativa al padre.

Para obtener el lado izquierdo, haga clic

 if(event.getRawX() <= (editComment.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) 

Muy, muy bien, gracias a todos los que contribuyeron a esta discusión. Entonces, si no quiere lidiar con la inconveniencia de extender la clase, puede hacer lo siguiente (implementado solo para el dibujable de la derecha)

 this.keyword = (AutoCompleteTextView) findViewById(R.id.search); this.keyword.setOnTouchListener(new RightDrawableOnTouchListener(keyword) { @Override public boolean onDrawableTouch(final MotionEvent event) { return onClickSearch(keyword,event); } }); private boolean onClickSearch(final View view, MotionEvent event) { // do something event.setAction(MotionEvent.ACTION_CANCEL); return false; } 

Y aquí está la implementación del oyente barebone basado en la respuesta de @ Mark

 public abstract class RightDrawableOnTouchListener implements OnTouchListener { Drawable drawable; private int fuzz = 10; /** * @param keyword */ public RightDrawableOnTouchListener(TextView view) { super(); final Drawable[] drawables = view.getCompoundDrawables(); if (drawables != null && drawables.length == 4) this.drawable = drawables[2]; } /* * (non-Javadoc) * * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent) */ @Override public boolean onTouch(final View v, final MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN && drawable != null) { final int x = (int) event.getX(); final int y = (int) event.getY(); final Rect bounds = drawable.getBounds(); if (x >= (v.getRight() - bounds.width() - fuzz) && x <= (v.getRight() - v.getPaddingRight() + fuzz) && y >= (v.getPaddingTop() - fuzz) && y <= (v.getHeight() - v.getPaddingBottom()) + fuzz) { return onDrawableTouch(event); } } return false; } public abstract boolean onDrawableTouch(final MotionEvent event); } 

Considera lo siguiente. No es la solución más elegante, pero funciona, acabo de probarlo.

  1. Cree una clase personalizada EditText CustomEditText.java :

     import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.EditText; 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(); //System.out.println("x:/y: "+x+"/"+y); //System.out.println("bounds: "+bounds.left+"/"+bounds.right+"/"+bounds.top+"/"+bounds.bottom); //check to make sure the touch event was within the bounds of the drawable 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 from coming up } } return super.onTouchEvent(event); } @Override protected void finalize() throws Throwable { dRight = null; rBounds = null; super.finalize(); } } 
  2. Cambie su diseño XML a esto (donde com.example es su nombre de paquete de proyecto real):

      
  3. Finalmente, agregue esto (o algo similar) a su actividad:

     … CustomEditText et = (CustomEditText) this.findViewById(R.id.txtsearch); … 

Puede que esté un poco decepcionado con el cálculo de los límites táctiles para el dibujo nested pero se entiende la idea.

Espero que esto ayude.

Creé una clase abstracta útil DrawableClickListener que implementa OnTouchListener .

Además de la clase DrawableClickListener , también creé 4 clases abstractas adicionales que extienden la clase DrawableClickListener y manejo el clic del área dibujable para el cuadrante correcto.

  • LeftDrawableClickListener
  • TopDrawableClickListener
  • RightDrawableClickListener
  • BottomDrawableClickListener

Punto para considerar

Una cosa a considerar es que las imágenes no se redimensionan si se hace de esta manera; por lo tanto, las imágenes deben escalarse correctamente antes de colocarlas en la (s) carpeta (s) res / dibujables .

Si define un LinearLayout que contiene un ImageView y un TextView , es mucho más fácil manipular el tamaño de la imagen que se muestra.


activity_my.xml

     

MyActivity.java

 package com.company.project.core; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MyActivity extends Activity { @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_my ); final TextView myTextView = (TextView) this.findViewById( R.id.myTextView ); myTextView.setOnTouchListener( new DrawableClickListener.LeftDrawableClickListener(myTextView) { @Override public boolean onDrawableClick() { // TODO : insert code to perform on clicking of the LEFT drawable image... return true; } } ); myTextView.setOnTouchListener( new DrawableClickListener.RightDrawableClickListener(myTextView) { @Override public boolean onDrawableClick() { // TODO : insert code to perform on clicking of the RIGHT drawable image... return true; } } ); } } 

DrawableClickListener.java

 package com.company.project.core; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.TextView; /** * This class can be used to define a listener for a compound drawable. * * @author Matthew Weiler * */ public abstract class DrawableClickListener implements OnTouchListener { /* PUBLIC CONSTANTS */ /** * This represents the left drawable. * */ public static final int DRAWABLE_INDEX_LEFT = 0; /** * This represents the top drawable. * */ public static final int DRAWABLE_INDEX_TOP = 1; /** * This represents the right drawable. * */ public static final int DRAWABLE_INDEX_RIGHT = 2; /** * This represents the bottom drawable. * */ public static final int DRAWABLE_INDEX_BOTTOM = 3; /** * This stores the default value to be used for the * {@link DrawableClickListener#fuzz}. * */ public static final int DEFAULT_FUZZ = 10; /* PRIVATE VARIABLES */ /** * This stores the number of pixels of "fuzz" that should be * included to account for the size of a finger. * */ private final int fuzz; /** * This will store a reference to the {@link Drawable}. * */ private Drawable drawable = null; /* CONSTRUCTORS */ /** * This will create a new instance of a {@link DrawableClickListener} * object. * * @param view * The {@link TextView} that this {@link DrawableClickListener} * is associated with. * @param drawableIndex * The index of the drawable that this * {@link DrawableClickListener} pertains to. * 
* use one of the values: * DrawableOnTouchListener.DRAWABLE_INDEX_* */ public DrawableClickListener( final TextView view, final int drawableIndex ) { this( view, drawableIndex, DrawableClickListener.DEFAULT_FUZZ ); } /** * This will create a new instance of a {@link DrawableClickListener} * object. * * @param view * The {@link TextView} that this {@link DrawableClickListener} * is associated with. * @param drawableIndex * The index of the drawable that this * {@link DrawableClickListener} pertains to. *
* use one of the values: * DrawableOnTouchListener.DRAWABLE_INDEX_* * @param fuzzOverride * The number of pixels of "fuzz" that should be * included to account for the size of a finger. */ public DrawableClickListener( final TextView view, final int drawableIndex, final int fuzz ) { super(); this.fuzz = fuzz; final Drawable[] drawables = view.getCompoundDrawables(); if ( drawables != null && drawables.length == 4 ) { this.drawable = drawables[drawableIndex]; } } /* OVERRIDDEN PUBLIC METHODS */ @Override public boolean onTouch( final View v, final MotionEvent event ) { if ( event.getAction() == MotionEvent.ACTION_DOWN && drawable != null ) { final int x = (int) event.getX(); final int y = (int) event.getY(); final Rect bounds = drawable.getBounds(); if ( this.isClickOnDrawable( x, y, v, bounds, this.fuzz ) ) { return this.onDrawableClick(); } } return false; } /* PUBLIC METHODS */ /** * * */ public abstract boolean isClickOnDrawable( final int x, final int y, final View view, final Rect drawableBounds, final int fuzz ); /** * This method will be fired when the drawable is touched/clicked. * * @return *
true if the listener has consumed the event; * false otherwise. * */ public abstract boolean onDrawableClick(); /* PUBLIC CLASSES */ /** * This class can be used to define a listener for a LEFT compound * drawable. * */ public static abstract class LeftDrawableClickListener extends DrawableClickListener { /* CONSTRUCTORS */ /** * This will create a new instance of a * {@link LeftDrawableClickListener} object. * * @param view * The {@link TextView} that this * {@link LeftDrawableClickListener} is associated with. */ public LeftDrawableClickListener( final TextView view ) { super( view, DrawableClickListener.DRAWABLE_INDEX_LEFT ); } /** * This will create a new instance of a * {@link LeftDrawableClickListener} object. * * @param view * The {@link TextView} that this * {@link LeftDrawableClickListener} is associated with. * @param fuzzOverride * The number of pixels of "fuzz" that should be * included to account for the size of a finger. */ public LeftDrawableClickListener( final TextView view, final int fuzz ) { super( view, DrawableClickListener.DRAWABLE_INDEX_LEFT, fuzz ); } /* PUBLIC METHODS */ public boolean isClickOnDrawable( final int x, final int y, final View view, final Rect drawableBounds, final int fuzz ) { if ( x >= ( view.getPaddingLeft() - fuzz ) ) { if ( x <= ( view.getPaddingLeft() + drawableBounds.width() + fuzz ) ) { if ( y >= ( view.getPaddingTop() - fuzz ) ) { if ( y <= ( view.getHeight() - view.getPaddingBottom() + fuzz ) ) { return true; } } } } return false; } } /** * This class can be used to define a listener for a TOP compound * drawable. * */ public static abstract class TopDrawableClickListener extends DrawableClickListener { /* CONSTRUCTORS */ /** * This will create a new instance of a {@link TopDrawableClickListener} * object. * * @param view * The {@link TextView} that this * {@link TopDrawableClickListener} is associated with. */ public TopDrawableClickListener( final TextView view ) { super( view, DrawableClickListener.DRAWABLE_INDEX_TOP ); } /** * This will create a new instance of a {@link TopDrawableClickListener} * object. * * @param view * The {@link TextView} that this * {@link TopDrawableClickListener} is associated with. * @param fuzzOverride * The number of pixels of "fuzz" that should be * included to account for the size of a finger. */ public TopDrawableClickListener( final TextView view, final int fuzz ) { super( view, DrawableClickListener.DRAWABLE_INDEX_TOP, fuzz ); } /* PUBLIC METHODS */ public boolean isClickOnDrawable( final int x, final int y, final View view, final Rect drawableBounds, final int fuzz ) { if ( x >= ( view.getPaddingLeft() - fuzz ) ) { if ( x <= ( view.getWidth() - view.getPaddingRight() + fuzz ) ) { if ( y >= ( view.getPaddingTop() - fuzz ) ) { if ( y <= ( view.getPaddingTop() + drawableBounds.height() + fuzz ) ) { return true; } } } } return false; } } /** * This class can be used to define a listener for a RIGHT compound * drawable. * */ public static abstract class RightDrawableClickListener extends DrawableClickListener { /* CONSTRUCTORS */ /** * This will create a new instance of a * {@link RightDrawableClickListener} object. * * @param view * The {@link TextView} that this * {@link RightDrawableClickListener} is associated with. */ public RightDrawableClickListener( final TextView view ) { super( view, DrawableClickListener.DRAWABLE_INDEX_RIGHT ); } /** * This will create a new instance of a * {@link RightDrawableClickListener} object. * * @param view * The {@link TextView} that this * {@link RightDrawableClickListener} is associated with. * @param fuzzOverride * The number of pixels of "fuzz" that should be * included to account for the size of a finger. */ public RightDrawableClickListener( final TextView view, final int fuzz ) { super( view, DrawableClickListener.DRAWABLE_INDEX_RIGHT, fuzz ); } /* PUBLIC METHODS */ public boolean isClickOnDrawable( final int x, final int y, final View view, final Rect drawableBounds, final int fuzz ) { if ( x >= ( view.getWidth() - view.getPaddingRight() - drawableBounds.width() - fuzz ) ) { if ( x <= ( view.getWidth() - view.getPaddingRight() + fuzz ) ) { if ( y >= ( view.getPaddingTop() - fuzz ) ) { if ( y <= ( view.getHeight() - view.getPaddingBottom() + fuzz ) ) { return true; } } } } return false; } } /** * This class can be used to define a listener for a BOTTOM compound * drawable. * */ public static abstract class BottomDrawableClickListener extends DrawableClickListener { /* CONSTRUCTORS */ /** * This will create a new instance of a * {@link BottomDrawableClickListener} object. * * @param view * The {@link TextView} that this * {@link BottomDrawableClickListener} is associated with. */ public BottomDrawableClickListener( final TextView view ) { super( view, DrawableClickListener.DRAWABLE_INDEX_BOTTOM ); } /** * This will create a new instance of a * {@link BottomDrawableClickListener} object. * * @param view * The {@link TextView} that this * {@link BottomDrawableClickListener} is associated with. * @param fuzzOverride * The number of pixels of "fuzz" that should be * included to account for the size of a finger. */ public BottomDrawableClickListener( final TextView view, final int fuzz ) { super( view, DrawableClickListener.DRAWABLE_INDEX_BOTTOM, fuzz ); } /* PUBLIC METHODS */ public boolean isClickOnDrawable( final int x, final int y, final View view, final Rect drawableBounds, final int fuzz ) { if ( x >= ( view.getPaddingLeft() - fuzz ) ) { if ( x <= ( view.getWidth() - view.getPaddingRight() + fuzz ) ) { if ( y >= ( view.getHeight() - view.getPaddingBottom() - drawableBounds.height() - fuzz ) ) { if ( y <= ( view.getHeight() - view.getPaddingBottom() + fuzz ) ) { return true; } } } } return false; } } }

El uso de la última contribución de contains(x,y) no funcionará directamente en el resultado de getBounds() (excepto, por coincidencia, cuando se usan los getBounds() “izquierdos”). El método getBounds solo proporciona los puntos de definición Rect del elemento Rect normalizado con origen en 0,0, por lo que, en realidad, debe hacer los cálculos de la publicación original para averiguar si el clic está en el área del dibujable en el contexto de las dimensiones de EditText que contienen, pero cámbialas por arriba, derecha, izquierda, etc. Como alternativa, podrías describir un Rect que tenga coordenadas realmente relativas a su posición en el contenedor EditText y usar contains() , aunque al final estás haciendo el mismas matemáticas

Combinarlos a ambos te da una solución bastante completa, solo agregué un atributo de instancia consumesEvent que permite al usuario API decidir si el evento click se debe pasar o no utilizando su resultado para establecer ACTION_CANCEL o no.

Además, no puedo ver por qué los bounds y los valores actionX , actionY son atributos de instancia en lugar de solo locales en la stack.

Aquí hay un recorte de una implementación basada en lo anterior que armé. Se soluciona un problema que para consumir correctamente el evento que necesita para devolver falso. Agrega un factor de “fuzz” a. En mi caso de uso de un icono de control de voz en un campo EditText , me resultó difícil hacer clic, por lo que el fuzz aumenta los límites efectivos que se consideran al hacer clic en el dibujante. Para mí 15 funcionó bien. Solo necesitaba drawableRight así que no conecté las matemáticas en las otras, para ahorrar espacio, pero ya ves la idea.

 package com.example.android; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.EditText; import android.graphics.Rect; import com.example.android.DrawableClickListener; public class ClickableButtonEditText extends EditText { public static final String LOG_TAG = "ClickableButtonEditText"; private Drawable drawableRight; private Drawable drawableLeft; private Drawable drawableTop; private Drawable drawableBottom; private boolean consumeEvent = false; private int fuzz = 0; private DrawableClickListener clickListener; public ClickableButtonEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public ClickableButtonEditText(Context context, AttributeSet attrs) { super(context, attrs); } public ClickableButtonEditText(Context context) { super(context); } public void consumeEvent() { this.setConsumeEvent(true); } public void setConsumeEvent(boolean b) { this.consumeEvent = b; } public void setFuzz(int z) { this.fuzz = z; } public int getFuzz() { return fuzz; } @Override public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) { if (right != null) { drawableRight = right; } if (left != null) { drawableLeft = left; } super.setCompoundDrawables(left, top, right, bottom); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { int x, y; Rect bounds; x = (int) event.getX(); y = (int) event.getY(); // this works for left since container shares 0,0 origin with bounds if (drawableLeft != null) { bounds = drawableLeft.getBounds(); if (bounds.contains(x - fuzz, y - fuzz)) { clickListener.onClick(DrawableClickListener.DrawablePosition.LEFT); if (consumeEvent) { event.setAction(MotionEvent.ACTION_CANCEL); return false; } } } else if (drawableRight != null) { bounds = drawableRight.getBounds(); if (x >= (this.getRight() - bounds.width() - fuzz) && x <= (this.getRight() - this.getPaddingRight() + fuzz) && y >= (this.getPaddingTop() - fuzz) && y <= (this.getHeight() - this.getPaddingBottom()) + fuzz) { clickListener.onClick(DrawableClickListener.DrawablePosition.RIGHT); if (consumeEvent) { event.setAction(MotionEvent.ACTION_CANCEL); return false; } } } else if (drawableTop != null) { // not impl reader exercise :) } else if (drawableBottom != null) { // not impl reader exercise :) } } return super.onTouchEvent(event); } @Override protected void finalize() throws Throwable { drawableRight = null; drawableBottom = null; drawableLeft = null; drawableTop = null; super.finalize(); } public void setDrawableClickListener(DrawableClickListener listener) { this.clickListener = listener; } } 

Es muy sencillo. Digamos que tiene un dibujante en el lado izquierdo de su EditText ‘txtsearch’. Lo siguiente hará el truco.

 EditText txtsearch = (EditText) findViewById(R.id.txtsearch); txtsearch.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() <= txtsearch.getTotalPaddingLeft()) { // your action for drawable click event return true; } } return false; } }); 

Si desea un drawable correcto, cambie la statement if a:

 if(event.getRawX() >= txtsearch.getRight() - txtsearch.getTotalPaddingRight()) 

Del mismo modo, puede hacerlo para todos los compuestos combinables.

 txtsearch.getTotalPaddingTop() txtsearch.getTotalPaddingBottom() 

Esta llamada a método devuelve todo el relleno de ese lado, incluidos los elementos extraíbles. Puedes usar esto incluso para TextView, Button, etc.

Haga clic aquí para consultar el sitio del desarrollador de Android.

Creo que es mucho más fácil si usamos algunos trucos 🙂

  1. Cree un botón de imagen con su icono y establezca el color de fondo para que sea transparente .
  2. Pon el botón de imagen en EditText y de coz en el lado derecho
  3. Implemente el oyente onclick del botón para ejecutar su función

Hecho

Ampliando la idea de RyanM he creado una versión más flexible, que admite todos los tipos dibujables (arriba, abajo, izquierda, derecha). Mientras que el siguiente código amplía TextView, adaptarlo a EditText es solo un caso de intercambio de “extends TextView” con “extends EditText”. La instanciación del widget desde XML es idéntica a la del ejemplo de RyanM, barra el nombre del widget.


 import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.TextView; import com.example.DrawableClickListener.DrawablePosition; public class ButtonTextView extends TextView { private Drawable drawableRight; private Drawable drawableLeft; private Drawable drawableTop; private Drawable drawableBottom; private int actionX, actionY; private DrawableClickListener clickListener; public ButtonTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public ButtonTextView(Context context, AttributeSet attrs) { super(context, attrs); } public ButtonTextView(Context context) { super(context); } @Override public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) { if (right != null) { drawableRight = right; } if (left != null) { drawableLeft = left; } if (top != null) { drawableTop = top; } if (bottom != null) { drawableBottom = bottom; } super.setCompoundDrawables(left, top, right, bottom); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { actionX = (int) event.getX(); actionY = (int) event.getY(); if (drawableBottom != null && drawableBottom.getBounds().contains(actionX, actionY)) { clickListener.onClick(DrawablePosition.BOTTOM); return super.onTouchEvent(event); } if (drawableTop != null && drawableTop.getBounds().contains(actionX, actionY)) { clickListener.onClick(DrawablePosition.TOP); return super.onTouchEvent(event); } if (drawableLeft != null && drawableLeft.getBounds().contains(actionX, actionY)) { clickListener.onClick(DrawablePosition.LEFT); return super.onTouchEvent(event); } if (drawableRight != null && drawableRight.getBounds().contains(actionX, actionY)) { clickListener.onClick(DrawablePosition.RIGHT); return super.onTouchEvent(event); } } return super.onTouchEvent(event); } @Override protected void finalize() throws Throwable { drawableRight = null; drawableBottom = null; drawableLeft = null; drawableTop = null; super.finalize(); } public void setDrawableClickListener(DrawableClickListener listener) { this.clickListener = listener; }} 

El DrawableClickListener es tan simple como esto:

 public interface DrawableClickListener { public static enum DrawablePosition { TOP, BOTTOM, LEFT, RIGHT }; public void onClick(DrawablePosition target); } 

Y luego la implementación real:

 class example implements DrawableClickListener { public void onClick(DrawablePosition target) { switch (target) { case LEFT: doSomethingA(); break; case RIGHT: doSomethingB(); break; case BOTTOM: doSomethingC(); break; case TOP: doSomethingD(); break; default: break; } }} 

ps: si no configuras el oyente, tocar TextView provocará una NullPointerException. Es posible que desee agregar algo más de paranoia en el código.

está funcionando para mí,

 mEditTextSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length()>0){ mEditTextSearch.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(android.R.drawable.ic_delete), null); }else{ mEditTextSearch.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.abc_ic_search), null); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); mEditTextSearch.setOnTouchListener(new OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_UP) { if(mEditTextSearch.getCompoundDrawables()[2]!=null){ if(event.getX() >= (mEditTextSearch.getRight()- mEditTextSearch.getLeft() - mEditTextSearch.getCompoundDrawables()[2].getBounds().width())) { mEditTextSearch.setText(""); } } } return false; } }); 

y si dibujable está a la izquierda, esto te ayudará. (para aquellos que trabajan con diseño RTL)

  editComment.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_LEFT = 0; final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP) { if (event.getRawX() <= (searchbox.getLeft() + searchbox.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) { // your action here return true; } } return false; } }); 

Simplemente copie y pegue el siguiente código y lo logra.

 editMsg.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_LEFT = 0; final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (editMsg.getRight() - editMsg.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { // your action here Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show(); return true; } } return false; } }); 

Sé que esto es bastante viejo, pero recientemente tuve que hacer algo similar … Después de ver lo difícil que es esto, se me ocurrió una solución mucho más simple:

  1. Crear un diseño XML que contenga EditText e Image
  2. Subclase FrameLayout e inflar el diseño XML
  3. Agregue código para el escucha de clic y cualquier otro comportamiento que desee

En mi caso, necesitaba un EditText que tuviera la capacidad de borrar el texto con un botón. Quería que se viera como SearchView, pero por una serie de razones no quería usar esa clase. El siguiente ejemplo muestra cómo logré esto. Aunque no tiene que ver con el cambio de enfoque, los principios son los mismos y pensé que sería más beneficioso publicar el código de trabajo real que armar un ejemplo que puede no funcionar exactamente como lo pretendía:

Aquí está mi diseño: clearable_edit_text.xml

      

Y aquí está la clase que infla ese diseño: ClearableEditText.java

 public class ClearableEditText extends FrameLayout { private boolean mPaddingSet = false; /** * Creates a new instance of this class. * @param context The context used to create the instance */ public ClearableEditText (final Context context) { this(context, null, 0); } /** * Creates a new instance of this class. * @param context The context used to create the instance * @param attrs The attribute set used to customize this instance */ public ClearableEditText (final Context context, final AttributeSet attrs) { this(context, attrs, 0); } /** * Creates a new instance of this class. * @param context The context used to create the instance * @param attrs The attribute set used to customize this instance * @param defStyle The default style to be applied to this instance */ public ClearableEditText (final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); final LayoutInflater inflater = LayoutInflater.from(context); inflater.inflate(R.layout.clearable_edit_text, this, true); } @Override protected void onFinishInflate () { super.onFinishInflate(); final EditText editField = (EditText) findViewById(R.id.edit_text_field); final ImageButton clearButton = (ImageButton) findViewById(R.id.edit_text_clear); //Set text listener so we can show/hide the close button based on whether or not it has text editField.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged (final CharSequence charSequence, final int i, final int i2, final int i3) { //Do nothing here } @Override public void onTextChanged (final CharSequence charSequence, final int i, final int i2, final int i3) { //Do nothing here } @Override public void afterTextChanged (final Editable editable) { clearButton.setVisibility(editable.length() > 0 ? View.VISIBLE : View.INVISIBLE); } }); //Set the click listener for the button to clear the text. The act of clearing the text will hide this button because of the //text listener clearButton.setOnClickListener(new OnClickListener() { @Override public void onClick (final View view) { editField.setText(""); } }); } @Override protected void onLayout (final boolean changed, final int left, final int top, final int right, final int bottom) { super.onLayout(changed, left, top, right, bottom); //Set padding here in the code so the text doesn't run into the close button. This could be done in the XML layout, but then if //the size of the image changes then we constantly need to tweak the padding when the image changes. This way it happens automatically if (!mPaddingSet) { final EditText editField = (EditText) findViewById(R.id.edit_text_field); final ImageButton clearButton = (ImageButton) findViewById(R.id.edit_text_clear); editField.setPadding(editField.getPaddingLeft(), editField.getPaddingTop(), clearButton.getWidth(), editField.getPaddingBottom()); mPaddingSet = true; } } } 

To make this answer more in line with the question the following steps should be taken:

  1. Change the drawable resource to whatever you want… In my case it was a gray X
  2. Add a focus change listener to the edit text…

Better to have ImageButton on Right of edit text and give negative layout margin to overlap with edit text. Set listener on ImageButton and perform operations.

 @Override public boolean onTouch(View v, MotionEvent event) { Drawable drawableObj = getResources().getDrawable(R.drawable.search_btn); int drawableWidth = drawableObj.getIntrinsicWidth(); int x = (int) event.getX(); int y = (int) event.getY(); if (event != null && event.getAction() == MotionEvent.ACTION_UP) { if (x >= (searchPanel_search.getWidth() - drawableWidth - searchPanel_search.getPaddingRight()) && x <= (searchPanel_search.getWidth() - searchPanel_search.getPaddingRight()) && y >= searchPanel_search.getPaddingTop() && y <= (searchPanel_search.getHeight() - searchPanel_search.getPaddingBottom())) { getSearchData(); } else { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(searchPanel_search, InputMethodManager.SHOW_FORCED); } } return super.onTouchEvent(event); } 
     

for left drawable click listener

 txt.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_LEFT = 0; if (event.getAction() == MotionEvent.ACTION_UP) { if (event.getRawX() <= (txt .getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width() + txt.getPaddingLeft() + txt.getLeft())) { //TODO do code here } return true; } } return false; } }); 

It is all great but why not to make it really simple?

I have faced with that also not so long ago…and android touchlistiner works great but gives limitation in usage..and I came to another solution and I hope that will help you:

                

enter image description here Now you can create ImageClick listener or event and do what ever you want with text. This edittext_round_corners.xml file

        

Compound drawables are not supposed to be clickable. It is cleaner to use separate views in a horizontal LinearLayout and use a click handler on them.

      

For anyone who does not want to implement the monstrous click handling. You can achieve the same with a RelativeLayout . With that you even have free handling of the positioning of the drawable.

        

The ImageView position will be the same as you would use drawableEnd – plus you don’t need all the touch listener handling. Just a click listener for the ImageView and you are good to go.

This works fro me:) may this help you as well

 edit_account_name.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (event.getRawX() >= (edit_account_name.getRight())) { //clicked return true; } } return false; } }); 

Here’s my simple solution, just place ImageButton over EditText :

     

I would like to suggest a way for drawable left! I tried this code and works.

 txtsearch.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { final int DRAWABLE_LEFT = 0; int start=txtsearch.getSelectionStart(); int end=txtsearch.getSelectionEnd(); if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() <= (txtsearch.getLeft() + txtsearch.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) { //Do your action here return true; } } return false; } }); } 

I implemented @aristo_sh answer in Mono.Droid (Xamarin), since it’s a delegate anonymous method you can’t return true or false you have to take take of e.Event.Handled. I am also hiding the keyboard on click

 editText.Touch += (sender, e) => { e.Handled = false; if (e.Event.Action == MotionEventActions.Up) { if (e.Event.RawX >= (bibEditText.Right - (bibEditText.GetCompoundDrawables()[2]).Bounds.Width())) { SearchRunner(); InputMethodManager manager = (InputMethodManager)GetSystemService(InputMethodService); manager.HideSoftInputFromWindow(editText.WindowToken, 0); e.Handled = true; } } }; 

Sharing my generalized solution for handling TextView compound drawable click and touch events.

First we need a touch event handler:

 /** * Handles compound drawable touch events. * Will intercept every event that happened inside (calculated) compound drawable bounds, extended by fuzz. * @see TextView#getCompoundDrawables() * @see TextView#setCompoundDrawablesRelativeWithIntrinsicBounds(int, int, int, int) */ public abstract class CompoundDrawableTouchListener implements View.OnTouchListener { private final String LOG_TAG = "CmpDrawableTouch"; private final int fuzz; public static final int LEFT = 0; public static final int TOP = 1; public static final int RIGHT = 2; public static final int BOTTOM = 3; private static final int[] DRAWABLE_INDEXES = {LEFT, TOP, RIGHT, BOTTOM}; /** * Default constructor */ public CompoundDrawableTouchListener() { this(0); } /** * Constructor with fuzz * @param fuzz desired fuzz in px */ public CompoundDrawableTouchListener(int fuzz) { this.fuzz = fuzz; } @Override public boolean onTouch(View view, MotionEvent event) { if (!(view instanceof TextView)) { Log.e(LOG_TAG, "attached view is not instance of TextView"); return false; } TextView textView = (TextView) view; Drawable[] drawables = textView.getCompoundDrawables(); int x = (int) event.getX(); int y = (int) event.getY(); for (int i : DRAWABLE_INDEXES) { if (drawables[i] == null) continue; Rect bounds = getRelativeBounds(i, drawables[i], textView); Rect fuzzedBounds = addFuzz(bounds); if (fuzzedBounds.contains(x, y)) { MotionEvent relativeEvent = MotionEvent.obtain( event.getDownTime(), event.getEventTime(), event.getAction(), event.getX() - bounds.left, event.getY() - bounds.top, event.getMetaState()); return onDrawableTouch(view, i, bounds, relativeEvent); } } return false; } /** * Calculates compound drawable bounds relative to wrapping view * @param index compound drawable index * @param drawable the drawable * @param view wrapping view * @return {@link Rect} with relative bounds */ private Rect getRelativeBounds(int index, @NonNull Drawable drawable, View view) { Rect drawableBounds = drawable.getBounds(); Rect bounds = new Rect(); switch (index) { case LEFT: bounds.offsetTo(view.getPaddingLeft(), view.getHeight() / 2 - bounds.height() / 2); break; case TOP: bounds.offsetTo(view.getWidth() / 2 - bounds.width() / 2, view.getPaddingTop()); break; case RIGHT: bounds.offsetTo(view.getWidth() - view.getPaddingRight() - bounds.width(), view.getHeight() / 2 - bounds.height() / 2); break; case BOTTOM: bounds.offsetTo(view.getWidth() / 2 - bounds.width() / 2, view.getHeight() - view.getPaddingBottom() - bounds.height()); break; } return bounds; } /** * Expands {@link Rect} by given value in every direction relative to its center * @param source given {@link Rect} * @return result {@link Rect} */ private Rect addFuzz(Rect source) { Rect result = new Rect(); result.left = source.left - fuzz; result.right = source.right + fuzz; result.top = source.top - fuzz; result.bottom = source.bottom + fuzz; return result; } /** * Compound drawable touch-event handler * @param v wrapping view * @param drawableIndex index of compound drawable which recicved the event * @param drawableBounds {@link Rect} with compound drawable bounds relative to wrapping view. * Fuzz not included * @param event event with coordinated relative to wrapping view - ie within {@code drawableBounds}. * If using fuzz, may return negative coordinates. */ protected abstract boolean onDrawableTouch(View v, int drawableIndex, Rect drawableBounds, MotionEvent event); } 

Now you can process any touch events on any compound drawable of any TextView you like this way:

 textView1.setOnTouchListener(new CompoundDrawableTouchListener() { @Override protected void onDrawableTouch(View v, int drawableIndex, Rect drawableBounds, MotionEvent event) { switch(v.getId()) { case R.id.textView1: switch(drawableIndex) { case CompoundDrawableTouchListener.RIGHT: doStuff(); break; } break; } } }); 

Only interested in clicks? Just filter out by MotionEvent action:

 /** * Handles compound drawable click events. * @see TextView#getCompoundDrawables() * @see TextView#setCompoundDrawablesRelativeWithIntrinsicBounds(int, int, int, int) * @see CompoundDrawableTouchListener */ public abstract class CompoundDrawableClickListener extends CompoundDrawableTouchListener { /** * Default constructor */ public CompoundDrawableClickListener() { super(); } /** * Constructor with fuzz * @param fuzz desired fuzz in px */ public CompoundDrawableClickListener(int fuzz) { super(fuzz); } @Override protected void onDrawableTouch(View v, int drawableIndex, Rect drawableBounds, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) onDrawableClick(v, drawableIndex); return true; } /** * Compound drawable touch-event handler * @param v wrapping view * @param drawableIndex index of compound drawable which recicved the event */ protected abstract void onDrawableClick(View v, int drawableIndex); } 

Again we can easily handle clicks on any compound drawable of any TextView:

 textView1.setOnTouchListener(new CompoundDrawableClickListener() { @Override protected void onDrawableClick(View v, int drawableIndex) { switch(v.getId()) { case R.id.textView1: switch(drawableIndex) { case CompoundDrawableTouchListener.RIGHT: doStuff(); break; } break; } } }); 

Hope you liked it as I did. I will try to keep it updated here and in related gist if anything changes.

I have created a simple custom touch listener class instead of a custom EditText

 public class MyTouchListener implements View.OnTouchListener { private EditText editText; public MyTouchListener(EditText editText) { this.editText = editText; setupDrawable(this.editText); } private void setupDrawable(final EditText editText) { editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length()>0) editText.setCompoundDrawablesWithIntrinsicBounds(0,0, R.drawable.clearicon,0); else editText.setCompoundDrawablesWithIntrinsicBounds(0,0, 0,0); } @Override public void afterTextChanged(Editable s) { } }); } @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_UP) { if(editText.getCompoundDrawables()[2]!=null){ if(event.getX() >= (editText.getRight()- editText.getLeft() - editText.getCompoundDrawables()[2].getBounds().width())) { editText.setText(""); } } } return false; } 

}

There will be no drawable when the EditText is blank. A drawable will show when we started editing for clear the EditText.

You can just set the touch listener

mEditText.setOnTouchListener(new MyTouchListener(mEditText));

I’ve seen several solutions but I wasn’t convinced by any of them. Either very complicated or too simple (non-reusable).

This is my favourite approach at the moment:

 mEditText.setOnTouchListener( new OnEditTextRightDrawableTouchListener(mEditText) { @Override public void OnDrawableClick() { // The right drawable was clicked. Your action goes here. } }); 

And this is the reusable touch listener:

 import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.EditText; public abstract class OnEditTextRightDrawableTouchListener implements OnTouchListener { private final EditText mEditText; public OnEditTextRightDrawableTouchListener(@NonNull final EditText editText) { mEditText = editText; } @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_UP) { final int DRAWABLE_RIGHT_POSITION = 2; final Drawable drawable = mEditText.getCompoundDrawables()[DRAWABLE_RIGHT_POSITION]; if (drawable != null) { final float touchEventX = motionEvent.getX(); final int touchAreaRight = mEditText.getRight(); final int touchAreaLeft = touchAreaRight - drawable.getBounds().width(); if (touchEventX >= touchAreaLeft && touchEventX <= touchAreaRight) { view.performClick(); OnDrawableClick(); } return true; } } return false; } public abstract void OnDrawableClick(); } 

You can look at the Gist here.

Follow below code for drawable right,left,up,down click:

 edittextview_confirmpassword.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_LEFT = 0; final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() >= (edittextview_confirmpassword.getRight() - edittextview_confirmpassword.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { // your action here edittextview_confirmpassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); return true; } }else{ edittextview_confirmpassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); } return false; } }); 

}

Solutions above work, but they have side affect. If you have an EditText with right drawable like

enter image description here

you will get a PASTE button after every click at the drawable. See How to disable paste in onClickListner for the Drawable right of an EditText android(inside icon EditText) .

So many solutions, but none worked for me when I had two fields in a row. This is drop in solution for adding clear button to edit text, worked for me in my situations where I have two fields or one field in a row. Written in kotlin !

 @SuppressLint("PrivateResource") fun  T.withClear(): T { addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable) { setCompoundDrawablesWithIntrinsicBounds(0, 0, if (editable.isNotEmpty()) abc_ic_clear_material else 0, 0) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit }) setOnTouchListener { _, event -> if (event.action == ACTION_UP && event.x >= (right - this.compoundPaddingRight)) { setText("") return@setOnTouchListener true } false } return this } 
  final TextView mTvTitle = (TextView)findViewById(R.id.tvTitle1); mTvTitle.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int DRAWABLE_LEFT = 0; final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP) { if(event.getRawX() <= (mTvTitle.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) { // your action here Intent intent = new Intent(DeAddExpences.this,DeHomeActivity.class); startActivity(intent); return true; } } return true; } });