Disable the keyboard when a button is pressed to close a fragment

How to close the keyboard by pressing a button? I have a snippet that has an EditText and two buttons. One represents the contents of the EditText, the other just closes the fragment. Now that the fragment has disappeared, the keyboard remains. However, pressing the back button closes the keyboard or pressing done also closes it. But I need the keyboard to disappear when the fragment is closed.

I tried solutions on similar issues here , here or here , but no one works. Most of them throw a NullPointerException . All of them are for action, not fragments. The code to call the keyboard works:

 editText.requestFocus(); InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT); 

However, I had to add getActivity () to make it work.

Any help would be appreciated.

+5
source share
3 answers

Use this method

 public void hideKeyboard() { // Check if no view has focus: View view = getActivity().getCurrentFocus(); if (view != null) { InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } 
+8
source

for fragment use the following function

  public static void hideKeyboard(Activity activity) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. View view = activity.getCurrentFocus(); //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = new View(activity); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } 

call it when the button is pressed

  btn_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { hideKeyboard(getActivity()); } }); 
+6
source

Try below method

 public static void hideKeyboard(Context mContext) { try { View view = ((Activity) mContext).getWindow().getCurrentFocus(); if (view != null && view.getWindowToken() != null) { IBinder binder = view.getWindowToken(); InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(binder, 0); } } catch (NullPointerException e) { e.printStackTrace(); } } 

In this method, you must pass a context parameter. Hope this helps you.

+1
source

Source: https://habr.com/ru/post/1265992/


All Articles