Skip to content

Instantly share code, notes, and snippets.

@Reacoder
Created August 5, 2014 05:27
Show Gist options
  • Save Reacoder/0b316726564f85523251 to your computer and use it in GitHub Desktop.
Save Reacoder/0b316726564f85523251 to your computer and use it in GitHub Desktop.
EditText onClick event is not triggering
When a user interacts with a UI element the various listeners are called in a top down order. (For example: OnTouch -> OnFocusChange -> OnClick.) If a listener has been defined (with setOn...Listener) and it consumes this event: the lower priority listeners will not be called. By its nature the first time you touch an EditText it receives focus with OnFocusChangeListener so that the user can type. The action is consumed here therefor OnClick is not called. Each successive touch doesn't change the focus so the event trickles down to the OnClickListener.
Basically, you have three choices:
Set the focusable attribute to false in your XML:
android:focusable="false"
Now the OnClickListener will fire every time it is clicked. But this makes the EditText useless since the user can no longer enter any text...
Implement an OnFocusChangeListener along with the OnClickListener:
ed1.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
Toast.makeText(getApplicationContext(), "onFocusChange", Toast.LENGTH_LONG).show();
}
});
Together you can catch every touch event on your EditText.
Implement an OnTouchListener by itself:
ed1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(MotionEvent.ACTION_UP == event.getAction())
Toast.makeText(getApplicationContext(), "onTouch: Up", Toast.LENGTH_SHORT).show();
return false;
}
});
This will execute every time the EditText is touched. Notice that this event returns a boolean. Returning false means that the event will continue trickle down and reach the built in onFocusChangeListener allowing it to receive text.
Hope that helps!
@anandprabhu04
Copy link

Thanks for the awesome tip !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment