Forked from codebreaker/RightDrawableOnTouchListener.java
Created
May 26, 2017 13:53
-
-
Save lcarlosilva/01f7dd4a63589543c1ce1c2196adf33c to your computer and use it in GitHub Desktop.
Click listener for compound drawables in Android.
From http://stackoverflow.com/questions/3554377/handling-click-events-on-a-drawable-within-an-edittext
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
this.keyword = (EditText) findViewById(R.id.search); | |
this.keyword.setOnTouchListener(new RightDrawableOnTouchListener(keyword) { | |
@Override | |
public boolean onDrawableTouch(final MotionEvent event) { | |
return onClickSearch(keyword); | |
} | |
}); | |
private boolean onClickSearch(final View view) { | |
// do something | |
event.setAction(MotionEvent.ACTION_CANCEL); | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment