How to hide the soft keyboard from inside a fragment?

前端 未结 14 1589
予麋鹿
予麋鹿 2020-12-01 00:08

I have a FragmentActivity using a ViewPager to serve several fragments. Each is a ListFragment with the following layout:



        
相关标签:
14条回答
  • 2020-12-01 00:35

    Use this static method, from anywhere (Activity / Fragment) you like.

    public static void hideKeyboard(Activity activity) {
        try{
            InputMethodManager inputManager = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            View currentFocusedView = activity.getCurrentFocus();
            if (currentFocusedView != null) {
                inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    

    If you want to use for fragment just call hideKeyboard(((Activity) getActivity())).

    0 讨论(0)
  • 2020-12-01 00:37

    This code works for fragments:

    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    
    0 讨论(0)
提交回复
热议问题