EditText OnClickListener requires two clicks to work
I have 4 EditTexts
in my activity. Each has an OnClickListener
that ticks a checkbox for me when called. However, when I press EditText for the first time, EditText
turns blue, but the checkbox is unchecked. Only when I press it again will
OnClickListener
take effect and check the box.
Who knows why?
Sample code:
public View.OnClickListener respiratoryOnClickListenerv(final View v) {
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
CheckBox respiratoryCheckbox = (CheckBox) v.findViewById(R.id.vitals_2);
respiratoryCheckbox.setChecked(true);
respiratoryCheckbox.callOnClick();
}
};
return listener;
}
respiratoryEditText.setOnClickListener(respiratoryOnClickListenerv(rootView));
Solution
When a user interacts with a UI element, various listeners are invoked in top-to-bottom order. (Example: OnTouch -> OnFocusChange -> OnClick.) If you already have a listener defined (using setOn…) listener) and it consumes this event: low-priority listeners will not be called. By its very nature, when you touch EditText for the first time, it gets focus through the OnFocusChangeListener so that the user can type. This operation is used here, so OnClick is not called. Each successive touch does not change focus, so events are passed down to OnClickListener.
From there, you have three options:
1) Set the focusable property to false:: in your XML
android:focusable=”false”
OnClickListener now fires every time you click. But this renders EditText useless because the user can no longer enter text.
2) Implement OnFocusChangeListener: with OnClickListener
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
Do your work
}
}
});
You can capture every touch event on EditText together.
3) Implement an OnTouchListener: yourself
editText.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 be executed every time the EditText is touched. Note that this event returns a boolean value. Returning false means that the event will continue to flow down and reach the built-in onFocusChangeListener to allow it to receive text.
Hope this helps!