Issue
I'm trying to popup an soft keyboard on the screen first load programmatically (not change windowSoftInputMode in Manifest).
The funny thing is on the screen first load, it didn't work at all. Here is the code block.
mEDT.requestFocus();
mEDT.requestFocusFromTouch();
mImm.showSoftInput(mEDT, InputMethodManager.SHOW_IMPLICIT);
The showSoftInput is return false, this cause the soft keyboard didn't show.
But when i click on the EditText. The showSoftInput return true and the soft keyboard was shown.
Can anyone explain to me what was happened ?
Solution
Are you using Fragments? I have found showSoftInput()
to be unreliable in Fragments.
After inspecting the source code, I discovered that calling requestFocus()
in onCreate()
/onCreateView()
or onResume()
does not immediately cause the object to be focused. This is most likely because the content View hasn't been created yet. So the focus happens sometime later during the initialization of the Activity or Fragment.
I have much more success calling showSoftInput()
in onViewCreated()
.
public class MyFragment extends Fragment {
private InputMethodManager inputMethodManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
EditText text1 = (EditText) view.findViewById(R.id.text1);
text1.requestFocus();
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view.findFocus(), InputMethodManager.SHOW_IMPLICIT);
super.onViewCreated(view, savedInstanceState);
}
}
Even if you aren't using Fragments, I bet the same rules apply. So make sure the View is created before calling showSoftInput().
Answered By - Ben
Answer Checked By - Cary Denson (JavaFixing Admin)