Hide to show and hide keyboard in DialogFragment
Asked Answered
A

8

14

In my dialog fragment, I am able to show the keyboard using

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT STATE_VISIBLE);

but I am not able to hide it on dismiss.

I've tried

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

and

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

neither of which work.

I've also tried showing and hiding the keyboard using

InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(0, 0); 

and

InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);

but these are not able to show or hide the keyboard.

 public static class MyDialogFragment extends DialogFragment
    {
        @Nullable @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            return inflater.inflate(R.layout.my_input_dialog, container, false);
        }

        @Override
        public void onViewCreated(View v, Bundle savedInstanceState)
        {
            super.onViewCreated(v, savedInstanceState);

            final EditText editText = (EditText)v.findViewById(R.id.input);
            // this line below is able to show the keyboard 
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); 
            Button add = (Button)v.findViewById(R.id.add_btn);
            add.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    // other code not shown
                    dismiss();
                }
            });
            Button cancel = (Button)v.findViewById(R.id.cancel_btn);
            cancelButton.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    dismiss();
                }
            });
        }

        @Override
        public void onDismiss(DialogInterface dialog)
        {
            //this line below does NOT work, it does not hide the keyboard
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            super.onDismiss(dialog);
        }
    }

Note: I have read these stackoverflow posts and have tried the proposed solutions to no avail:

  1. How to hide the onscreen keyboard when a DialogFragment is canceled by the setCanceledOnTouchOutside event
  2. Close/hide the Android Soft Keyboard
Abessive answered 18/1, 2017 at 17:30 Comment(0)
A
35

The solution turned out to a combination of the following. To show the keyboard in a DialogFragment:

    @Override
    public void onResume()
    {
        super.onResume();
        editText.post(new Runnable()
        {
            @Override
            public void run()
            {
                editText.requestFocus();
                InputMethodManager imm =
                    (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null)
                    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
            }
        });
    }

To hide it, use the solution above by @Shekhar

    @Override
    public void onDismiss(DialogInterface dialog)
    {
        InputMethodManager imm =
            (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive())
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        super.onDismiss(dialog);
    }
Abessive answered 18/1, 2017 at 18:31 Comment(4)
Finally! It was getting the context from the edittext that I was missing. Thank you!Joann
Sometimes, when I show and dismiss dialog quickly, keyboard remains visible. Any ideas?Demarcusdemaria
It is realy important to place it in onDismiss. E.g. by onStop it does not work, how everHarsho
Interestingly, the imm.showSoftInput(editText,InputMethodManager.SHOW_IMPLICIT) doesn't work if not called within post{}, but why?Eleonoreeleoptene
G
6

Hiding keyboard in a View inside DialogFragment:

public static void hideKeyboardInAndroidFragment(View view){
        final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Gerianne answered 26/1, 2018 at 17:57 Comment(0)
R
4

For Hiding the Keyboard use this:

 private void hideKeyboard() {
        try {
            InputMethodManager inputManager = (InputMethodManager) _activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(_activity.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
        }
}
Rondon answered 18/1, 2017 at 17:32 Comment(1)
Thanks, I upvoted this, but this is not the full answer. This only answers part of the question (hiding). Note that this answer does not work to close the keyboard when the keyboard was opened using ` getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);` See my answer below for the solution to my problem.Abessive
B
2

for hide soft keyboard, you can use this method:

public void hideSoftKeyboard() {
        try {
            View windowToken = getDialog().getWindow().getDecorView().getRootView();
            InputMethodManager imm = (InputMethodManager) getDialog().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow( windowToken.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception ex) {
            Log.e(ex);
        }
    }
Bjorn answered 15/3, 2019 at 9:40 Comment(1)
finally this one worked in dialogfragment, thanksZilpah
Z
0

Hide it in DialogFragment onDestroyView() method:

 View view = getActivity().getCurrentFocus();
        if (view == null) view = new View(activity);
        InputMethodManager imm = (InputMethodManager)     getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

maybe work.

Zaibatsu answered 7/12, 2017 at 7:14 Comment(0)
J
0

I had extension for fragment, but didn't work with dialog fragment. This extension works for both (not tested much tho)

/**
 * If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
 *
 * @param useReflection - whether to use reflection in case of no window token or not
 */
fun Fragment.hideKeyboard(context: Context = App.instance, useReflection: Boolean = true) {
    val windowToken = view?.rootView?.windowToken
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    windowToken?.let {
        imm.hideSoftInputFromWindow(windowToken, 0)
    } ?: run {
        if (useReflection) {
            try {
                if (getKeyboardHeight(imm) > 0) {
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                }
            } catch (exception: Exception) {
                Timber.e(exception)
            }
        }
    }
}

fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int

Edit: toggle opened keyboard if it was closed before, I use reflection to get keyboard's height, which is not best solution, but works

Journal answered 24/10, 2018 at 7:18 Comment(0)
H
0

I found only one fully working approach if you want to show keyboard when dialog is shown and hide keyboard when dialog is dismissed

<style name="InputDialog" parent="ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="android:windowSoftInputMode">stateAlwaysVisible</item>
</style>

And then you should use the theme above inside your DialogFragment

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NORMAL, R.style.InputDialog)
}
Holton answered 11/12, 2020 at 15:40 Comment(0)
S
-1

Kotil Extension function for DialogFragment hide keyboard

 use : hideKeyboard(view)
fun DialogFragment.hideKeyboard(view: View) {
    val imm =view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}
Sputnik answered 17/9, 2019 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.