How to hide the soft keyboard from inside a fragment?

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

    Nothing of this worked on API27. I had to add this in the container of the layout, for me it was a ConstraintLayout:

    <android.support.constraint.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:focusedByDefault="true">
    
    //Your layout
    
    </android.support.constraint.ConstraintLayout>
    
    0 讨论(0)
  • 2020-12-01 00:24

    Use this code in any fragment button listener:

    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
    
    0 讨论(0)
  • 2020-12-01 00:24

    Use this:

    Button loginBtn = view.findViewById(R.id.loginBtn);
    loginBtn.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
          InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
       }
    });
    
    0 讨论(0)
  • 2020-12-01 00:31

    In Kotlin:

    (activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view?.windowToken,0)
    
    0 讨论(0)
  • 2020-12-01 00:32

    Exception for DialogFragment though, focus of the embedded Dialog must be hidden, instead only the first EditText within the embedded Dialog

    this.getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    
    0 讨论(0)
  • 2020-12-01 00:34
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_my, container,
                    false);
            someClass.onCreate(rootView);
            return rootView;
        }
    

    Keep an instance of my root view in my class

    View view;
    
    public void onCreate(View rootView) {
        view = rootView;
    

    Use the view to hide the keyboard

     public void removePhoneKeypad() {
        InputMethodManager inputManager = (InputMethodManager) view
                .getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
    
        IBinder binder = view.getWindowToken();
        inputManager.hideSoftInputFromWindow(binder,
                InputMethodManager.HIDE_NOT_ALWAYS);
    }
    
    0 讨论(0)
提交回复
热议问题