Android TextField : set focus + soft input programmatically

Good sir, try this:

edittext.setFocusableInTouchMode(true);
edittext.requestFocus();

I'm not sure, but this might be required on some phones (some of the older devices):

final InputMethodManager inputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(edittext, InputMethodManager.SHOW_IMPLICIT);

Here is the code that worked for me.

edittext.post(new Runnable() {
    public void run() {
        edittext.requestFocusFromTouch();
        InputMethodManager lManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
        lManager.showSoftInput(edittext, 0);
    }
});

That's it! Enjoy ;)


The following code worked for me, after the other two answers didn't work for me:

@Override
public void onResume() {
    super.onResume();
    SingletonBus.INSTANCE.getBus().register(this);
    //passwordInput.requestFocus(); <-- that doesn't work
    passwordInput.postDelayed(new ShowKeyboard(), 300); //250 sometimes doesn't run if returning from LockScreen
}

Where ShowKeyboard is

private class ShowKeyboard implements Runnable {
    @Override
    public void run() {
        passwordInput.setFocusableInTouchMode(true);
  //      passwordInput.requestFocusFromTouch();
        passwordInput.requestFocus();            
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0);
    }
}

After a successful input, I also make sure I hide the keyboard

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getView().getWindowToken(), 0);

Technically, I just added 300 ms of delay before running the soft keyboard display request. Weird, right? Also changed requestFocus() to requestFocusFromTouch().

EDIT: Don't use requestFocusFromTouch() it gives a touch event to the launcher. Stick with requestFocus().

EDIT2: In Dialogs (DialogFragment), use the following

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

instead of

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);