How to hide the soft keyboard from inside a fragment?

前端 未结 14 1588
予麋鹿
予麋鹿 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:14

    If you add the following attribute to your activity's manifest definition, it will completely suppress the keyboard from popping when your activity opens. Hopefully this helps:

    (Add to your Activity's manifest definition):

    android:windowSoftInputMode="stateHidden"
    
    0 讨论(0)
  • 2020-12-01 00:15

    As long as your Fragment creates a View, you can use the IBinder (window token) from that view after it has been attached. For example, you can override onActivityCreated in your Fragment:

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
    }
    
    0 讨论(0)
  • 2020-12-01 00:16

    Nothing but the following line of code worked for me:

    getActivity().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    
    0 讨论(0)
  • 2020-12-01 00:17

    This worked for me in Kotlin class

    fun hideKeyboard(activity: Activity) {
        try {
            val inputManager = activity
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            val currentFocusedView = activity.currentFocus
            if (currentFocusedView != null) {
                inputManager.hideSoftInputFromWindow(currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    
    }
    
    0 讨论(0)
  • 2020-12-01 00:18

    this will be work in my case when in tabs i switch from one fragment to another fragments

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            try {
                InputMethodManager mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                mImm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
                mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
            } catch (Exception e) {
                Log.e(TAG, "setUserVisibleHint: ", e);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 00:18

    Just add this line in you code:

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