When we have an EditText
and it loses focus (to an element that doesn\'t need a keyboard), should the soft keyboard hide automatically or are we supposed to hid
Just create one static method
public static void touchScreenAndHideKeyboardOnFocus(View view, final Activity activity) {
if (view instanceof EditText) {
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(activity != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
}
});
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
touchScreenAndHideKeyboardOnFocus(innerView, activity);
}
}
}
view is a root view for your layout.. but be careful, if you have another focus listener in your edittext..
my problem solved with this code (in Fragment)
LinearLayout linearLayoutApply=(LinearLayout)rootView.findViewById(id.LinearLayoutApply);
linearLayoutApply.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
{
hideKeyBoard(v);
}
}
});
hideKeyBoard
public void hideKeyBoard(View v)
{
InputMethodManager imm=(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
Solution to this problem has already been found here.
It is using DispatchTouchEvent on activity and does not hook every EditText to either FocusChange or Touch event.
It is much better solution.
My Xamarin implementation is as follows:
public override bool DispatchTouchEvent(MotionEvent ev)
{
if (ev.Action == MotionEventActions.Down)
{
var text = CurrentFocus as EditText;
if (text != null)
{
var outRect = new Rect();
text.GetGlobalVisibleRect(outRect);
if (outRect.Contains((int) ev.RawX, (int) ev.RawY)) return base.DispatchTouchEvent(ev);
text.ClearFocus();
HideSoftKeyboard();
}
}
return base.DispatchTouchEvent(ev);
}
protected void HideSoftKeyboard()
{
var inputMethodManager = (InputMethodManager) GetSystemService(InputMethodService);
inputMethodManager.HideSoftInputFromWindow(CurrentFocus.WindowToken, 0);
}