3

I've been trying to automatically show the keyboard with focus on a edit text when a fragment(that includes the edittext) is loaded.

I've tried using :

     editTextPrice.requestFocus();
    InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imgr.showSoftInput(getView(), InputMethodManager.SHOW_IMPLICIT);

But this doesn't work the first time I load the fragment. The focus is set and I can see the cursor but no keyboard appears. If I close the fragment and add it again it works.

If tried everything from post() to a postpone it with a handler, to onResume,ect.

Does anybody have an idea what might cause this to happen?

Thanks in advance.

Best regards

Patric
  • 342
  • 4
  • 19

4 Answers4

2

let me explain why keyboard is not opening when we load a fragment the view cannot get focused, so we need set focus to the view in a separate thread, Then after we need to open keyBoard

void showKeyboard(Context mContext, View view)
{
    if (mContext != null && view != null && view.requestFocus())
    {
        InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}

This above function is to open keyboard

editTextPrice.postDelayed(() -> {
        editTextPrice.requestFocus();
    showKeyboard(getContext(), editTextPrice);
    }, 300);
0
android:focusable="true"
android:focusableInTouchMode="true"

And

EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
Suhas Bachewar
  • 1,230
  • 7
  • 21
0

you try using 2 function below:

   fun hideKeyBoard(context: Context, view: View) {
        val inputMethodManager = context.getSystemService(
            Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
    }

    fun showKeyBoard(context: Context, view: View) {
        val inputMethodManager = context.getSystemService(
            Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }
Tuan Dao
  • 99
  • 5
0

Do not request focus from java code. Do it from the xml itself like

android:focusable="true" 

also do the following in the manifest file

<activity android:name=".YourActivity"
    android:windowSoftInputMode="stateAlwaysVisible" />
Anbarasu Chinna
  • 975
  • 9
  • 28