solalito
solalito

Reputation: 1209

Hiding keyboard when switching tab in the action bar

I used to be using TabHost to set up my tabs but following people's advice I rewrote my code using the ActionBar.Tab. In my older version of the code, I hid the keyboard when switching tabs the following way:

// Hide Keyboard when changing tab
    th.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            switch (th.getCurrentTab()) {
            case 0:
                imm.hideSoftInputFromWindow(tab1.getWindowToken(), 0);
                break;
            case 2:
                imm.hideSoftInputFromWindow(tab1.getWindowToken(), 0);
                break;
            }
        }
    });

I tried using a similar approach but I don't know how to getWindowToken for my ActionBar.Tab. Any suggestions?

Upvotes: 1

Views: 415

Answers (1)

Anna Billstrom
Anna Billstrom

Reputation: 2492

if(mActivity.getCurrentFocus() != null) {
        InputMethodManager imm = (InputMethodManager)mActivity.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), 0);
    }

Get the current focus, and use that to get the Window Token. My listener is passing in a fragment and activity (mActivity) and so I used that to get what's focused.

Upvotes: 1

Related Questions