89

In my view, I have a search EditText and I would like to trigger programmatically the behaviour of a click event on the field, i.e give focus to the text field AND display soft keyboard if necessary (if no hard keyboard available).

I tried field.requestFocus(). The field actually gets focus but soft keyboard is not displayed.

I tried field.performClick(). But that only calls the OnClickListener of the field.

Any idea ?

sdabet
  • 18,360
  • 11
  • 89
  • 158

8 Answers8

155

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);
Simson
  • 3,373
  • 2
  • 24
  • 38
pgsandstrom
  • 14,361
  • 13
  • 70
  • 104
  • 3
    Same result as requestFocus() alone... Field gets focus but the soft keyboard is not triggered. – sdabet Nov 10 '11 at 14:03
  • 12
    I finally solved the issued by calling `field.requestFocus()` in the `onResume()` method of the activity (instead of the `onCreate()`). Don't exactly know why it works... – sdabet Nov 10 '11 at 14:28
  • 31
    A view cannot take focus before it actually has been laid out on the screen. This cannot be done while onCreate() holds the UI-thread, therefore the view is laid out directly after onCreate() and before onResume(). :) – pgsandstrom Nov 10 '11 at 14:40
  • @fiddler It works in `onResume` because `onResume` is called after `onCreate`, so `field` doesn't exist until `onCreate` is run. See here: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle – Randy Dec 24 '13 at 17:28
  • thnx man .. giving focus to the edit text in onResume method works for me. – Rana Ranvijay Singh May 06 '14 at 06:16
  • 3
    Excellent suggestion, ol' chap. I do declare; this is well deserving of an upvote! – MW. Apr 20 '15 at 10:57
  • @pgsandstrom but in my app the soft keyboard is not triggered too. I use fragment and call this in onViewCreated methode! – roghayeh hosseini Dec 14 '20 at 09:00
66

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 ;)

elisabel
  • 668
  • 6
  • 4
  • 2
    Thanks and this one worked for me. I add `EditText` programmatically when user hits button. – dumbfingers May 02 '13 at 09:55
  • I added an `EditText` from a dialog modal. Some flags are getting set by Android that cause this control to not receive any touches. If you add the field in the runnable, the flags don't get set. – JeffRegan Jul 24 '14 at 15:42
  • It looks like the `InputType` of the `EditText` is being set to null by Android. If you set the `InputType`, it should work. – JeffRegan Jul 24 '14 at 16:06
  • The only working solution for me (if I use InputMethodManager to show keyboard forced, then I can't hide it) – Pavel May 27 '17 at 23:16
  • None of the other methods worked for me, but this one did. I wanted to have a box for users to click in to open the edit dialogue view instead of having an edit line to click for an EditText view. On a phone the edit line loses most of it's functionality as the edit dialogue view covers then entire screen, so the user can't see the edit line, including the letters going in it while they are typing, anyway. – Androidcoder Oct 24 '17 at 18:05
7

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);
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • `requestFocusFromTouch()` seems to trigger a touch event on the launcher. This is weird. – EpicPandaForce Mar 27 '15 at 08:31
  • For hiding the keyboard, does the ((InputMethodManager) getActivity()..." code line also need to change for use in a DialogFragment or is the code line you mention above sufficient? – AJW Jul 20 '21 at 18:55
  • It should most likely work but you can always try it and see – EpicPandaForce Jul 21 '21 at 06:01
2

In my case, I wanted to display the virtual keyboard with no reference to a specific textbox, so I used the first part of the accepted answer to focus :

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

Then I show the virtual keyboard :

InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
DependencyHell
  • 1,027
  • 15
  • 22
1

for kotlin, implement using extension function as follow

fun View.showSoftKeyboard() {
    this.requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
kroegerama
  • 769
  • 9
  • 27
puskal Khadka
  • 113
  • 2
  • 6
0
        field.post(new Runnable() {
            @Override
            public void run() {
                field.requestFocus();
                field.onKeyUp(KeyEvent.KEYCODE_DPAD_CENTER, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER));
            }
        });
Intra
  • 46
  • 1
  • 4
0

In my case just this solved all problems:

val inputMethodManager: InputMethodManager = 
   context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(edittext, InputMethodManager.SHOW_IMPLICIT)

I have put it in RecyclerView Adapter, because I use data binding. Also I haven't used edittext.setFocusableInTouchMode(true) because in my layout it is true by default. And don't use this line: edittext.requestFocus(). When I removed it, it started to work :)

Peter Z.
  • 159
  • 1
  • 5
0

val mAlertDialog = mBuilder.show()

        //Coloca o foo no txtDlgQuantidade e então chama o teclado
        mDialogView.txtDlgQuantidade.isFocusable = true
        mDialogView.txtDlgQuantidade.isFocusableInTouchMode = true
        mDialogView.txtDlgQuantidade.requestFocus()
        mAlertDialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        mAlertDialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)