Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing Soft Keyboard in Fragment

I found a number of answers to this question but none of them are working for me. I have an Edit text in my Fragment, which gets launched when the application starts. When this Fragment opens, the soft keyboard pops up as well. How do I prevent that from happening? This is what I have in my onCreateView method in my Fragment....

        try {
        InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(userName.getWindowToken(), 0);
    }catch(Exception e) {
        e.printStackTrace();
    }
like image 662
Mark F Avatar asked Jan 22 '16 23:01

Mark F


People also ask

How do you force close a keyboard?

You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow , passing in the token of the window containing your focused view. This will force the keyboard to be hidden in all situations. In some cases, you will want to pass in InputMethodManager.

How do you move the layout when the soft keyboard is showing Android fragment?

How do you move the layout up when the soft keyboard is shown Android fragment? Well, one solution to achieve this is to put everything inside a ScrollView and just scroll up to the required position when the keyboard appears. Detect keyboard is open.


2 Answers

Try this in onCreateView or onActivityCreated.

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
like image 128
Jay Rathod RJ Avatar answered Oct 16 '22 23:10

Jay Rathod RJ


My recently project I use the code as follow to hide the keyboard layout, maybe you can try it.(I learn it from the source code of Wordpress-android)

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_template_add_doc, container, false);
    //hide the keyboard if it is visible
    InputMethodManager imm = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
    return view;
}
like image 22
Xin Meng Avatar answered Oct 16 '22 23:10

Xin Meng