Show keyboard for edittext when fragment starts

When my fragment starts, I want my edittext to be in focus/let user to just start typing in it. I am able to get it in focus with requestFocus(), but I cannot get the keyboard to show up.

I have tried both this:

edit = (EditText) view.findViewById(R.id.search);
edit.requestFocus();
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);

and

edit = (EditText) view.findViewById(R.id.search);
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);
edit.requestFocus();

How can I get the keyboard to show up for EditText?


Solution 1:

Does this work?

imgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

Solution 2:

You can try this

@Override
public void onResume() {
    super.onResume();
    edit.post(new Runnable() {
        @Override
        public void run() {
            edit.requestFocus();
            InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imgr.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT);
        }
    });
}

Solution 3:

Since using showSoftInput doesn't work for all cases and after trying some of the solutions mentioned here, like:

if (binding.account.requestFocus()) {
  requireActivity().getWindow()
      .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}

I finally made it work using:

if (binding.account.requestFocus()) {
  ((InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(
      InputMethodManager.SHOW_FORCED,
      InputMethodManager.HIDE_IMPLICIT_ONLY
  );
}

Since:

 binding.account.requestFocus()

only request the focus for the EditText (it doesn't open the keyboard)

and

((InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(
      InputMethodManager.SHOW_FORCED,
      InputMethodManager.HIDE_IMPLICIT_ONLY
  );

is the only solution that appears to be working correctly to show the keyboard (and the most voted one)

Good luck! :-)