Lars D
Lars D

Reputation: 8573

Hide soft keyboard on activity without any keyboard operations

I have a tabbed view with one Activity per tab, and when I switch from the first tab, which has a TextView, to the second tab, which only shows a clickable list, the soft keyboard is still there. I want it to go away, so I tried this:

public static void hideSoftKeyboard (Activity activity, View view) {
  InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

but this does not work, because there is no relevant view to provide, as there is no View on the screen that takes keyboard input. Any suggestions on how to solve this?

Upvotes: 6

Views: 19671

Answers (6)

pratt
pratt

Reputation: 1813

I had a similar issue when try to hide keyboard while transition animation playing.

This worked for me:

imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0)

Upvotes: 0

Hitesh Bhalala
Hitesh Bhalala

Reputation: 2870

This method may help you to hide keyboard any way. This is working fine for me

public void hideKeyboard(Activity activity, View view) {
        if (activity != null ) {

            if(view != null)
            {
                try {
                    InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else
            {
                activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            }

        }
    }

Upvotes: 0

Richard Le Mesurier
Richard Le Mesurier

Reputation: 29762

Try the answer provided by Joe on: Stop EditText from gaining focus at Activity startup

Place this inside the manifest for your activity: android:windowSoftInputMode="stateHidden"

This is a common question, and it is great to know that the framework actually handles this very nicely.

Upvotes: 16

muzaffar
muzaffar

Reputation: 71

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

Upvotes: 4

Roman Nazarevych
Roman Nazarevych

Reputation: 7703

You can also try

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0 );

Upvotes: 4

Sergey Glotov
Sergey Glotov

Reputation: 20356

Try this in 3rd line of your code:

imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);

Upvotes: 16

Related Questions