Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide keyboard when navigating from a fragment to another

I have a Fragment that contains an Edit Text. When the Edit Text is pressed, the keyboard is being shown. When pressed the Save button in the upper corner, the application returns to the previous fragment, but the keyboard persists.

I would like the keyboard to be hidden when navigating to the previous fragment.

Please, note that I tried this solution: Close/hide the Android Soft Keyboard.

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(myView.getWindowToken(), 0); 

I tried to use this in both fragments, in the onCreate method.

I also tried to hide the soft keyboard in the layout:

android:windowSoftInputMode="stateAlwaysHidden" 

None of these worked, unfortunately.

I would have posted some pictures, but I do not have enough reputation yet. I would appreciate any constructive help and opinion and do not forget that "A wise man can learn more from a foolish question than a fool can learn from a wise answer." :)

Regards, Alexandra

like image 620
Alexandra Alstanei Avatar asked Nov 13 '14 14:11

Alexandra Alstanei


Video Answer


2 Answers

Put the code that hides the keyboard in your "save button" click listener, and use this method to hide the keyboard:

    public static void hideKeyboard(Activity activity) {         InputMethodManager inputManager = (InputMethodManager) activity         .getSystemService(Context.INPUT_METHOD_SERVICE);          // check if no view has focus:          View currentFocusedView = activity.getCurrentFocus();          if (currentFocusedView != null) {              inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);          }      } 
like image 124
Silvia H Avatar answered Oct 13 '22 00:10

Silvia H


Kotlin

For Kotlin, you can use this as a top level function, just add the code to a separate class such as Utils.kt.

fun hideKeyboard(activity: Activity) {     val inputMethodManager =         activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager      // Check if no view has focus     val currentFocusedView = activity.currentFocus     currentFocusedView?.let {         inputMethodManager.hideSoftInputFromWindow(             currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)     } } 

To access it from Fragment, call it like:

hideKeyboard(activity as YourActivity) 

Thanks to Silvia H for Java code.

like image 43
Yogesh Umesh Vaity Avatar answered Oct 12 '22 22:10

Yogesh Umesh Vaity