I have a fragment with a single EditText that needs the soft keyboard to remain open continually. The keyboard gets hidden when the screen is rotated. I'm calling showSoftInput in OnActivityCreated which gets executed after the rotation, but it doesn't show the keyboard.

InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, 0);

Note: I don't want to use toggleSoftInput. I've tried that but it ends up closing the keyboard in some instances. And there's no way to query android to determine if the keyboard is already open.

有帮助吗?

解决方案

It appears that showSoftInput is very buggy with Fragments.

First try @TronicZomB's solution. It works for an Activity with a single Fragment.

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

However, for an Activity with nested FragmentTransactions, you'll be forced to use toggleSoftInput with the SHOW_FORCED and HIDE_NOT_ALWAYS parameters. HIDE_NOT_ALWAYS prevents the toggle command from closing the already opened keyboard after an orientation change.

InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);

To hide the keyboard at a later time, you can use:

imm.hideSoftInputFromWindow(activity.findViewById(android.R.id.content).getWindowToken(), 0);

其他提示

Try replacing the InputMethodManager with the following:

 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top