Problem
Sometimes we the Keyboard doesn’t show up by default if we e.g. open a dialog and request the focus for an input element. Even following the default tutorials doesn’t really help. As soo here some samples how it will show up.
Solution
Show Keyboard in Dialogs / DialogFragment
Usually the solution the the Android Guide just works using:
Solution 1
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Get field from view mEditText = (EditText) view.findViewById(R.id.txt_your_name); // Show soft keyboard automatically and request focus to field mEditText.requestFocus(); getDialog().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); }
Solution 2
My personal experience was, that this (solution 1) isn’t really working always — more the happy case. More reliable is the following solution:
@NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Dialog dialog = super.onCreateDialog(savedInstanceState); // show the keyboard as soon we get the focus ... dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialogInterface) { txtInput.post(new Runnable() { @Override public void run() { final InputMethodManager imm = (InputMethodManager) txtInput.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(txtInput, InputMethodManager.SHOW_IMPLICIT); txtInput.requestFocus(); // needed if you have more then one input } }); } }); return dialog; }
This solutions also just works with the normal AlertDialog
as it uses the show listener.
Important to note is, that in either case requestFocus should either be called or set in the xml layout file for the element.
Solution 3: Always show they Keyboard
Where is alway the possibility to always show the keyboard — even if not always really useful:
getDialog().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
The keyboard could now be shown even if the user can’t input something into any input element. Where in solution 2 the keyboard is only shown of the element gets the focus, in this case the keyboard is just shown.
Request Focus for an Element using XML Layout File
Just add the Tag <requestFocus />
to the body of the element.
<EditText android:id="@+id/txtInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text"> <requestFocus /> </EditText>
You are right that first solution did not work some times.
In my case always first solution did not work but your second solution always works.
Thanks for help.
You are right that first solution did not work some times.
In my case always first solution did not work but your second solution always works.
Thanks for help.