jaimin
jaimin

Reputation: 23

SoftKeyboard Hide issue in Fragment

TASK : Have to hide Soft_Keyboard when user comes back from Recent to Application. (Taking about coming back to Fragment from Recent), There should no Soft_Keyboard in open mode.

ISSUE : Soft_keyboard remains open when i am coming back from recent mode.

EFFORTS : To hide soft_keyboard I have done below lines of Code in onStart(), onResume(), onCreate() and also in my custom method init() inside Fragment.

CODE : as below :

  1. CALL : CommonUtil.hideSoftKeyboard(getActivity());
  2. Lines :

     public static void hideSoftKeyboard(Context context) {
            try {
                InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
                    View focusedView = ((Activity) context).getCurrentFocus();
                    //If no view is focused, an NPE will be thrown
                    if (focusedView != null) {
                        inputMethodManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), 0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    

.. I have tried above code in [enter code] but, it still looks like this: hope you can understood.

Anyway,

What might be the solution ? Thanks.

NOTE : I don't wanna to use ADJUST_PAN. ;)

Upvotes: 0

Views: 44

Answers (2)

Denis
Denis

Reputation: 653

When the fragment is no longer visible, the EditText View still retains the focus so the keyboard remains visible. However; When the fragment transitions from visible to no longer visible execution can be intercepted as follows:

...

override fun onStop() {
// Fragment transitions from visible to not visible
super.onStop()
hideSoftKeyboard()}
    
fun hideSoftKeyboard(){
myEditTextView1.clearFocus()
myEditTextView2.clearFocus()
//etc
}
    

...

If you cannot be sure which Edit textview has the focus you must clearFocus() on all views as you move from one fragment to another. This worked for me like a charm....

Upvotes: 0

Rajasekaran M
Rajasekaran M

Reputation: 2538

I'm also getting same issue when try to close the soft-keyboard from Fragment but I solved with passing the view which is having the focus and below code works fine for me.

  public void hideKeyboard(View view) {
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

Upvotes: 0

Related Questions