the editText is not losing focus in my app when I click out of it, it has the orange border all time and that black line cursor..
I did this a LinearLayout according to this surrounding the editText:
Stop EditText from gaining focus at Activity startup
so it doesn't get focus on start of the app..
this is my code:
final EditText et = (EditText)findViewById(R.id.EditText01);
final InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
et.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
}
});
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasfocus) {
if(hasfocus) {
imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
} else {
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
}
});
But, it doesn't seem to be calling the onFocusChange when I click anywhere outside the editText!
It's simple. You can put the following in LinearLayout or any other else:
android:focusableInTouchMode="true"
Override Activity.dispatchTouchEvent()
:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View view = getCurrentFocus();
if (view != null && view instanceof EditText) {
Rect r = new Rect();
view.getGlobalVisibleRect(r);
int rawX = (int)ev.getRawX();
int rawY = (int)ev.getRawY();
if (!r.contains(rawX, rawY)) {
view.clearFocus();
}
}
}
return super.dispatchTouchEvent(ev);
}
That way, whenever someone clicks anywhere, you have control, and it's at only one point in code.
Create an onClick
listener, possibly in your XML layout to listen for clicks in the background LinearLayout. From here you can call .clearFocus()
on your EditText
after you make it an instance variable of the activity you are working in.
You can remove the focus from the EditText, by setting the focus to other field by calling the method.
Suppose I have set the focus to back button on click of done button, then call the method on back button inside done button click listener.
And your problem is solved.
back.requestFocusFromTouch();