当前位置: 动力学知识库 > 问答 > 编程问答 >

Hide keyboard when switching tabs in android

问题描述:

I have created tab strip with custom classes and I am displaying one fragment in each strip but when keyboard is open and I switch to tab then second fragment is getting called but the keyboard is not hiding.

I am using this in onCreateView() in both fragment but its not working :

//To Hide Soft KeyBoard

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

网友答案:

Use this class to hide and show keyboard at runtime. Try to call the method on your onTabChangedListener. Hope it helps.

public class KeyBoardHandler {

    public static void hideSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }

    public static void showSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
}
网友答案:

Put this code in onDestroy method of fragment.

try {
        InputMethodManager mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mImm.hideSoftInputFromWindow(mView.getWindowToken(), 0);
        mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

    } catch (Exception e) {

    }
网友答案:

Try with below code

Interface: ICallBacks

public interface ICallBacks {
  public void isChanged();
}

In your activity define on variable like

public ICallBacks mCallbacks;

In OnPageChangeListener

 @Override
public void onPageScrolled(int arg0, float arg1, int arg2) {


    if (mCallbacks != null)
        mCallbacks.isChanged();
}

In your fragment you need to implement with ICallBacks interface

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    if (activity != null) {
        ((PagerActivity) getActivity()).mCallbacks = this;
    }

}
@Override
public void isChanged() {

    if (isVisible())
        hideKeyboard();
}

    private void hideKeyboard() {
      InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
      View view = this.getCurrentFocus();
      if (view != null) {
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
分享给朋友:
您可能感兴趣的文章:
随机阅读: