542

I want to automatically show the soft-keyboard when an EditText is focused (if the device does not have a physical keyboard) and I have two problems:

  1. When my Activity is displayed, my EditText is focused but the keyboard is not displayed, I need to click again on it to show the keyboard (it should be displayed when my Activity is displayed).

  2. And when I click done on the keyboard, the keyboard is dissmissed but the EditText stays focused and y don't want (because my edit is done).

To resume, my problem is to have something more like on the iPhone: which keep the keyboard sync with my EditText state (focused / not focused) and of course does not present a soft-keyboard if there is a physical one.

Ludovic Landry
  • 11,606
  • 10
  • 48
  • 80
  • I just have a basic EditText like: And on my activity I have this: EditText editTxt = (EditText) findViewById(R.id.myEditText); editTxt.requestFocus(); – Ludovic Landry Feb 24 '11 at 14:40
  • 2
    This helped me better than any answer in this post : http://stackoverflow.com/a/2418314/1491212 – Armel Larcier Sep 30 '13 at 18:07

48 Answers48

743

To force the soft keyboard to appear, you can use

EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
yourEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

And for removing the focus on EditText, sadly you need to have a dummy View to grab focus.


To close it you can use

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);

This works for using it in a dialog

public void showKeyboard(){
    InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

public void closeKeyboard(){
    InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
raukodraug
  • 11,519
  • 4
  • 35
  • 37
  • 3
    If I do this, the soft-keyboard is shown when the activity appears (it's good) but when my focus leave the EditText and go to a Button for example, the keyboard stays (that's bad). – Ludovic Landry Feb 24 '11 at 15:14
  • 1
    So, I need to check my EditText focus, there is no automatic way to do that. I think it's just because the android philosophy about the keyboard is different than the Apple one on the iPhone. – Ludovic Landry Feb 24 '11 at 16:45
  • so, does this help your problem? – raukodraug Feb 24 '11 at 17:16
  • 180
    Doesn't work for me with an EditText in a dialog which already has focus. Not sure why. – mxk Mar 11 '13 at 16:02
  • 1
    Yes @Matthias I have an edittext on a dialog and the keyboard doesn't show up even after using the code above, any solutions ? – Abdellah Benhammou May 24 '13 at 13:06
  • 10
    @AbdellahBenhammou, perhaps doing a requestFocus call onn your edit text before showing the soft input might solve your issue. It did for me. – r1k0 Jul 10 '13 at 14:38
  • 18
    @AbdellahBenhammou, do this in your DialogFragment's onCreate(): getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); – Phillip Aug 05 '13 at 06:26
  • 2
    Complete n00b question: What happens on devices with physical keyboards, is the soft keyboard shown as well? – Ricardo Zea Oct 24 '13 at 16:19
  • 1
    @Phillip just make sure to call this BEFORE you call Dialog.show() and it works real good using SOFT_INPUT_S‌​TATE_VISIBLE – shkschneider Mar 04 '14 at 15:26
  • @Phillip NPE when used in DialogFragment.onCreate(), but it works in DialogFragment.onCreateDialog(): AlertDialog dialog = builder.create(); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); return dialog; – peceps Sep 02 '14 at 15:08
  • 23
    Worked only in conjunction with ```yourEditText.requestFocus()``` as described here: http://stackoverflow.com/questions/8991522/how-can-i-set-the-focus-and-display-the-keyboard-on-my-edittext-programmatic – Vivek Pandey Sep 11 '14 at 07:41
  • And then how to get focus on keyboard? – Dr.jacky Nov 09 '15 at 10:57
  • 2
    I got the soft keyboard to appear in a pop up by coding like this AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); AlertDialog alert = alertDialog.show(); alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); – Kiran Muralee Feb 25 '16 at 10:16
  • 2
    This worked for me only when I wrapped the `requestFocus()` / `showSoftInput()` in a `postDelayed` handler, as in the other top answer. This is on Android 6.0 with a support lib `EditText`. – Matt Zukowski Mar 07 '16 at 17:58
  • You have to use InputMethodManager.SHOW_FORCED instead of InputMethodManager.SHOW_IMPLICIT if the keyboard doesn't show up. – Matjaz Kristl Sep 19 '18 at 05:39
  • 2
    This wasn't working until I moved my code from `onCreateView` to `onViewCreated`. If it's in `onCreateView` you need to delay execution of `showSoftInput` – RandomEngy Aug 15 '19 at 05:50
  • 3
    I"m still encountering this issue in 2021, this is probably the most annoying issue in the whole framework – DennisVA Feb 17 '21 at 16:34
265

I had the same problem. Immediately after editText VISIBILITY change from GONE to VISIBLE, I had to set the focus and display the soft keyboard. I achieved this using the following code:

new Handler().postDelayed(new Runnable() {
            
    public void run() {
//        ((EditText) findViewById(R.id.et_find)).requestFocus();
//              
        EditText yourEditText= (EditText) findViewById(R.id.et_find);
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

        yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
        yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));                          
    }
}, 200);

It works for me with 100ms delay, but failed without any delay or with only a delay of 1ms.

Commented part of code shows another approach, which works only on some devices. I tested on OS versions 2.2 (emulator), 2.2.1 (real device) and 1.6 (emulator).

This approach saved me a lot of pain.

Leo DroidCoder
  • 14,527
  • 4
  • 62
  • 54
Mike Keskinov
  • 11,614
  • 6
  • 59
  • 87
  • 60
    I didn't know something could be so ugly and so beautiful at the same time. Thank you so much! – mkerley Mar 21 '12 at 21:46
  • 17
    @jellyfish this simulates a tap on the `EditText`. For others reading this, instead of creating a new `Handler` you could also use the `View.postDelayed()` method on the `yourEditText` widget itself. – Tony Chan Sep 20 '12 at 19:02
  • I found I needed a longer delay or it would not work 1st time on some devices; I'm using 500 ms. (Not a CPU speed issue, e.g. one problem device was Nexus 7 which is plenty fast) – mwk Jan 20 '13 at 22:57
  • 5
    This is a hack - much better solution by David Chandler. – Ben Bederson Feb 23 '13 at 18:53
  • 4
    If David Chandler's solution works across all Android versions/devices and for the case when VISIBILITY was just changed from GONE to VISIBLE, then YES - you should use his solution instead. – Mike Keskinov Feb 24 '13 at 04:41
  • 3
    Agreed. Do you know better solution which works across all Android flavors? – Mike Keskinov Apr 03 '13 at 14:12
  • The last 2 lines made the text to be selected, on 4.4. without them the code worked fine. – user1940676 Jan 29 '14 at 09:10
  • 1
    @user1940676 to move the cursor to the end of the text add this at the end: `yourEditText.setSelection(yourEditText.getText().length());` Or you can set the cursor to the beginning by passing in `0` instead of `length()`. – Tony Chan Apr 19 '14 at 00:54
  • 1
    There are 100's of solutions to this problem, if the EditText is inside a dialog, your solution is the only one that works, I couldn't thank you enough – Kaan Soral Jul 05 '15 at 19:13
  • I was using the classic `InputMethodManager#showSoftInput()` method but it didn't work until I moved the code into a call to `View#postDelayed()`, inspired by your answer. Thanks – Mickäel A. Sep 11 '18 at 14:16
  • I used set setOnShowListener instead of using a delay and that worked out much better. – dt0 Mar 11 '19 at 14:04
  • 2
    Perfect! Worked for me in DialogFragment even without posting it delayed. +1 – Shahood ul Hassan Mar 13 '19 at 18:57
  • with the 500 ms delay instead of 200, it works like a charm on Android 12! – Hossein Farrokhi Nov 22 '22 at 10:24
168

To cause the keyboard to appear, use

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

This method is more reliable than invoking the InputMethodManager directly.

To close it, use

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Community
  • 1
  • 1
David Chandler
  • 2,397
  • 1
  • 17
  • 12
  • 14
    Can somebody please explain why this is more reliable than directly invoking `InputMethodManager`? (For one, it doesn't work, unlike raukodraug's solution.) – Matthew Quiros May 03 '13 at 08:00
  • 5
    Does not work for me either. Working in Android 2.3.5. raukodraug's solution does work for me. Searched for version dependency but could not find one. – Hugo Logmans May 06 '13 at 13:38
  • 2
    This worked for me in Android 4.4.2. The InputMethodManager method chosen as the solution for this post did not work for me. – Phil Mar 10 '14 at 22:58
  • after using the method in the answer i appended this and it worked,but without it it didnt work. thanx – Manny265 Jul 13 '14 at 21:22
  • 2
    Didn't work for me in Android 4.4.2. It shows the keyboard but didn't hide it. – John J Smith Jul 22 '14 at 21:19
  • Didn't work for me. Had to use InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(searchInputBox, InputMethodManager.SHOW_IMPLICIT); – marienke Mar 24 '15 at 12:02
  • At least for me this worked after I placed it BEFORE the EditText.requestFocus() and finally the Dialog.show(). – frezq Feb 08 '16 at 14:21
  • It shows keyboard of incorrect type (not related to the focused control). – Dmitry Aug 31 '18 at 19:58
  • The only advice that worked on my Huawei/Android 7.0. Thanks a lot! – Dmitry Negoda Aug 07 '19 at 08:33
106

When nothing else works, force it to be shown:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

And then later, if you wish to close it, in onPause() for example, you can call:

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
Bolling
  • 3,954
  • 1
  • 27
  • 29
77

The following code is pillaged from the Google's 4.1 source code for SearchView. Seems to work, fine on lesser versions of Android as well.

private Runnable mShowImeRunnable = new Runnable() {
    public void run() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            imm.showSoftInput(editText, 0);
        }
    }
};

private void setImeVisibility(final boolean visible) {
    if (visible) {
        post(mShowImeRunnable);
    } else {
        removeCallbacks(mShowImeRunnable);
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindowToken(), 0);
        }
    }
}

Then in addition, the following code needs to be added as the Control/Activity is created. (In my case it's a composite control, rather than an activity).

this.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
        setImeVisibility(hasFocus);
    }
});
TWiStErRob
  • 44,762
  • 26
  • 170
  • 254
Robin Davies
  • 7,547
  • 1
  • 35
  • 50
  • Thanks! It works amazingly well. And it's the solution I'm more comfortable with from all the answers and topics I've been reading on this issue. – Rui Jan 22 '13 at 19:38
  • 37
    :-D `setImeVisibility(hasFocus)`? – mxk Mar 11 '13 at 16:04
  • I tried this method since I was actually "rolling my own search view" (didn't want to have to do that but there were reasons). This worked for me except for at launch of the activity. I added android:windowSoftInputMode="alwaysVisible" to the activity and already had requestFocus() being called on the edit text. Works like a champ. – javahead76 Mar 22 '13 at 16:09
  • Any idea the need of removeCallbacks(mShowImeRunnable) ? I thought once the runnable is picked to run from queue, it will be removed from the queue at the same time as well? – Cheok Yan Cheng Mar 31 '13 at 03:55
  • Re: removeCallbacks: that code was lifted pretty much verbatim from Google sources, but it makes sense to me. If the last call from the foreground thread to setImeVisibility has the visible parameter set to false, you definitely don't want the posted Runnable to execute afterward. Re: setImeVisibility(hasFocus). :-P Yes. – Robin Davies Jul 10 '13 at 01:06
  • This solution does not work for me.. My situation is: edit text is gone, and when I set it to visible, I want to show the soft-keyboard. Can anyone share, if this should work in such cases also. Thx – Sandra Feb 24 '14 at 12:38
  • Cool, it works like a charm. I just add a requestFocus() on my view before the showSoftInput() call because I don't call setImeVisibility(true) in an onFocusChange listener – vincentp May 24 '14 at 17:02
  • 2
    After trying several variations, this was the only one that worked consistently for me (Android 4.42). Thx – John J Smith Jul 22 '14 at 21:34
  • @RobinDavies FYI you can use the @ symbol followed by a user name to tag someone so other users don't have to cross-reference the entire conversation to understand what you are attempting to accomplish. – Abandoned Cart Apr 14 '17 at 19:08
  • 1
    +1 - regarding what the exact question is this is the most complete and correct answer and should be the accepted answer – greyhairredbear Dec 04 '19 at 09:54
36

android:windowSoftInputMode="stateAlwaysVisible" -> in manifest File.

edittext.requestFocus(); -> in code.

This will open soft keyboard on which edit-text has request focus as activity appears.

Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82
gorenikhil33
  • 385
  • 3
  • 4
32

I have had some recent luck in some simple cases with the code below. I haven't finished all testing but....

EditText input = (EditText) findViewById(R.id.Input);
input.requestFocus();    
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));

And presto the keyboard shows up.

Leo DroidCoder
  • 14,527
  • 4
  • 62
  • 54
Dent
  • 400
  • 1
  • 4
  • 8
  • For my case I had a button to add some optional information. In the button.onClick handler the above code was added to force the soft keyboard to appear for the input of the optional info. Droid 2.2.2 – Dent Oct 18 '11 at 23:22
  • this is a good solution but do not forget that you should create a MotionEvent object and call recycle() on them after usage, to be re-used by a later caller. – jimbob Nov 15 '14 at 09:37
  • You just need one dispatchTouchEvent() with ACTION_UP as its argument.. – Mohammed Junaid May 06 '19 at 22:29
20

You can try to force the soft keyboard to appear, it works for me:

...
dialog.show();
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Vadim Zin4uk
  • 1,716
  • 22
  • 18
  • 1
    This works for me ... I had tried these InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(name, inputMethodManager.SHOW_IMPLICIT); or getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); but none of them were working. – Günay Gültekin Jan 24 '16 at 12:38
17

And for Kotlin just use this extensions:

fun EditText.showKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun EditText.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}
bitvale
  • 1,959
  • 1
  • 20
  • 27
11

For fragment, sure its working:

 displayName = (EditText) view.findViewById(R.id.displayName);
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Arish Khan
  • 254
  • 4
  • 10
10

Sometimes raukodraug's answer won't work. I've make it in this way with some trials and errors:

public static void showKeyboard(Activity activity) {
    if (activity != null) {
        activity.getWindow()
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}

public static void hideKeyboard(Activity activity) {
    if (activity != null) {
        activity.getWindow()
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

And the EditText part:

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                hideKeyboard(getActivity());
            } else {
                showKeyboard(getActivity());
            }
        }
    });
Xieyi
  • 1,316
  • 1
  • 14
  • 19
10

showSoftInput was not working for me at all.

I figured I needed to set the input mode: (here in the Activity component in the manifest)

android:windowSoftInputMode="stateVisible" 
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
vincebodi
  • 547
  • 5
  • 4
10

To hide keyboard, use this one:

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

and to show keyboard:

getActivity().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Mubashar
  • 333
  • 6
  • 15
  • For a DialogFragment, you can call this in an overridden `onStart()`, and you can use `getDialog().getWindow()` as an alternative to `getActivity().getWindow()`. – Mr-IDE Aug 06 '18 at 18:30
10

Kotlin extension for showing the keyboard on focus.

This is a combination of previous responses, which where either too long or incomplete.

This extension posts a runnable on the message queue which shows the soft keyboard after requesting focus:

fun View.showSoftKeyboard() {
    post {
        if (this.requestFocus()) {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
        }
    }
}

Call it from any view when needed afterwards:

editText.showSoftKeyboard()
Alex Burdusel
  • 3,015
  • 5
  • 38
  • 49
8

Simply add this line in your EditText view:

android:isScrollContainer="true"

and TADA - keyboard began to show up automatically!

I had similar problem and discovered this simple and strange solution.

As already was mentioned here by user3392439, appearance of the keyboard upon focus somehow wierdly connected with presense of the scroll component in the XML file.

Even presence of another EditText view which comprises abovementioned line in same XML makes keyboard appear no matter which one of EditTexts is currently focused.

If you have at least one visible view comprising scroll component in your XML file - keyboard will appear automatically on focus.

If no scroll - then you need to click on EditText to make keyboard appear.

Waldmann
  • 1,563
  • 12
  • 25
7

Here's a more reliable solution i got from Square:

fun View.focusAndShowKeyboard() {
   /**
    * This is to be called when the window already has focus.
    */
   fun View.showTheKeyboardNow() {
       if (isFocused) {
           post {
               // We still post the call, just in case we are being notified of the windows focus
               // but InputMethodManager didn't get properly setup yet.
               val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
               imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
           }
       }
   }

   requestFocus()
   if (hasWindowFocus()) {
       // No need to wait for the window to get focus.
       showTheKeyboardNow()
   } else {
       // We need to wait until the window gets focus.
       viewTreeObserver.addOnWindowFocusChangeListener(
           object : ViewTreeObserver.OnWindowFocusChangeListener {
               override fun onWindowFocusChanged(hasFocus: Boolean) {
                   // This notification will arrive just before the InputMethodManager gets set up.
                   if (hasFocus) {
                       this@focusAndShowKeyboard.showTheKeyboardNow()
                       // It’s very important to remove this listener once we are done.
                       viewTreeObserver.removeOnWindowFocusChangeListener(this)
                   }
               }
           })
   }
}

Code credits from here.

Steve Kamau
  • 2,755
  • 10
  • 42
  • 73
6

I had the same problem in various different situations, and the solutions i have found work in some but dont work in others so here is a combine solution that works in most situations i have found:

public static void showVirtualKeyboard(Context context, final View view) {
    if (context != null) {
        final InputMethodManager imm =  (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        view.clearFocus();

        if(view.isShown()) {
            imm.showSoftInput(view, 0);
            view.requestFocus();
        } else {
            view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                @Override
                public void onViewAttachedToWindow(View v) {
                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            view.requestFocus();
                            imm.showSoftInput(view, 0);
                        }
                    });

                    view.removeOnAttachStateChangeListener(this);
                }

                @Override
                public void onViewDetachedFromWindow(View v) {
                    view.removeOnAttachStateChangeListener(this);
                }
            });
        }
    }
}
n0sferat0k
  • 71
  • 1
  • 1
6

I combined everything here and for me it works:

public static void showKeyboardWithFocus(View v, Activity a) {
    try {
        v.requestFocus();
        InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
        a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Mike
  • 4,550
  • 4
  • 33
  • 47
lxknvlk
  • 2,744
  • 1
  • 27
  • 32
6
editText.post(new Runnable() {
    @Override
    public void run() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
});
Mike
  • 4,550
  • 4
  • 33
  • 47
Guest
  • 71
  • 2
  • 3
6

It worked for me. You can try with this also to show the keyboard:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Tarit Ray
  • 944
  • 12
  • 24
6

Believe or not my problem with Soft Keyboard was resolved when I discovered that the Activities animations can disable the Soft Keyboard. When you call the intent with the

i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

and

overridePendingTransition(0, 0);

It can hide the Soft Keyboard and there isn't a way to show it.

Marvin Pinto
  • 30,138
  • 7
  • 37
  • 54
sparkbit
  • 61
  • 2
  • 4
5

code snippet . . .

public void hideKeyboard(Context activityContext){

    InputMethodManager imm = (InputMethodManager)
            activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);

    //android.R.id.content ( http://stackoverflow.com/a/12887919/2077479 )
    View rootView = ((Activity) activityContext)
            .findViewById(android.R.id.content).getRootView();

    imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0);
}

public void showKeyboard(Context activityContext, final EditText editText){

    final InputMethodManager imm = (InputMethodManager)
            activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);

    if (!editText.hasFocus()) {
        editText.requestFocus();
    }

    editText.post(new Runnable() {
        @Override
        public void run() {
            imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        }
    });
}
Jongz Puangput
  • 5,527
  • 10
  • 58
  • 96
5

Inside your manifest:

android:windowSoftInputMode="stateAlwaysVisible" - initially launched keyboard. android:windowSoftInputMode="stateAlwaysHidden" - initially hidden keyboard.

I like to use also "adjustPan" because when the keyboard launches then the screen auto adjusts.

 <activity
      android:name="YourActivity"
      android:windowSoftInputMode="stateAlwaysHidden|adjustPan"/>
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Md Imran Choudhury
  • 9,343
  • 4
  • 62
  • 60
4

just add android:windowSoftInputMode="stateHidden" in manifest file...

4
final InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
XXX
  • 8,996
  • 7
  • 44
  • 53
4

None of the Answers worked for me. Here is a simple way.

searchEditText.setVisibility(View.VISIBLE);
                final Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        searchEditText.requestFocus();
                    }
                }, 400);

Just delayed the requestFocus() method for 400ms.

Satyajit
  • 625
  • 7
  • 12
3

All solutions given above (InputMethodManager interaction in OnFocusChangeListener.onFocusChange listener attached to your EditText works fine if you have single edit in the activity.

In my case I have two edits.

 private EditText tvX, tvY;
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 tvX.setOnFocusChangeListener(this);
    tvY.setOnFocusChangeListener(this);

@Override
public void onFocusChange(View v, boolean hasFocus) {       
    InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if(tvX.hasFocus() || tvY.hasFocus()) {            
        imm.showSoftInput(v, 0);            
    } else {
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);         
    }       
};

I have observed that onFocusChange is triggered for tvX with hasFocus=true (keyboard shown) but then for tvY with hasFocus=true (keyboard hidden). In the end, no keyboard was visible.

General solution should have correct statement in if "show keyboard if EditText text has focus"

Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113
3

In your onResume() section of the Activity you can do call the method bringKeyboard();

 onResume() {
     EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
     bringKeyboard(yourEditText);
 }


  protected boolean bringKeyboard(EditText view) {
    if (view == null) {
        return false;
    }
    try {
      // Depending if edittext has some pre-filled values you can decide whether to bring up soft keyboard or not
        String value = view.getText().toString();
        if (value == null) {
            InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            return true;
        }
    } catch (Exception e) {
        Log.e(TAG, "decideFocus. Exception", e);
    }
    return false;
  }
Vikas
  • 4,263
  • 1
  • 34
  • 39
3

As I read on the official document, I think this is the best answer, just pass the View to parameter such as your EditText, but showSoftKeyboard seems like not working on landscape

private fun showSoftKeyboard(view: View) {
    if (view.requestFocus()) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }
}

private fun closeSoftKeyboard(view: View) {
    if (view.requestFocus()) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}
Thành Thỏ
  • 173
  • 1
  • 8
3

For Kotlin:

val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

fun showKeyboard() {
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
    }

fun hideKeyboard() {
        imm.hideSoftInputFromWindow(phoneNoInputTxt.windowToken, 0);
    }

Then just call what you want!

Jamil Hasnine Tamim
  • 4,389
  • 27
  • 43
2

If EditText is inside Recycler or ListView and/or this have disable state use below code.

public static void showKeyboardByFocus(final View view)
    {
        view.requestFocus();

        InputMethodManager keyboard = SystemMaster.getInputMethodManager();
        keyboard.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);

        Runnable re = new Runnable()
        {
            @Override
            public void run()
            {
                view.setEnabled(true);
                view.requestFocus();
            }
        };

        Handler h = new Handler(Looper.getMainLooper());
        h.postDelayed(re, 360);
    }
Ali Bagheri
  • 3,068
  • 27
  • 28
2

I use this extension function for showing the keyboard with Kotlin.

fun EditText.requestFocusWithKeyboard() {
    post {
        dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0))
        dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0))
        setSelection(length())
    }
}

You can just call it as:

editText.requestFocusWithKeyboard()

Besides being very convenient:

  1. You don't have to worry about closing it in all the possible cases, such as when you navigate back with InputMethodManager.SHOW_FORCED.
  2. In addition to request focus, it also sets the selection (cursor to the end of text)
Leo DroidCoder
  • 14,527
  • 4
  • 62
  • 54
1

I discovered a strange behaviour, since in one of my apps, the soft keyboard was automatically showing on entering the activity (there is an editText.requestFocus() in onCreate).

On digging further, I discovered that this was because there is a ScrollView around the layout. If I remove the ScrollView, the behaviour is as described in the original problem statement: only on clicking the already focused editText does the soft keyboard show up.

If it doesn't work for you, try putting in a ScrollView -- it's harmless anyway.

user3392439
  • 973
  • 8
  • 6
1

I had a similar problem using view animations. So I've put an animation listener to make sure I'd wait for the animation to end before trying to request a keyboard access on the shown edittext.

    bottomUp.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (textToFocus != null) {
                // Position cursor at the end of the text
                textToFocus.setSelection(textToFocus.getText().length());
                // Show keyboard
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(textToFocus, InputMethodManager.SHOW_IMPLICIT);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });
Benjamin Piette
  • 3,645
  • 1
  • 27
  • 24
1

I am agree with raukodraug therefor using in a swithview you must request/clear focus like this :

    final ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
    final View btn = viewSwitcher.findViewById(R.id.address_btn);
    final View title = viewSwitcher.findViewById(R.id.address_value);

    title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            viewSwitcher.showPrevious();
            btn.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(btn, InputMethodManager.SHOW_IMPLICIT);
        }
    });

    // EditText affiche le titre evenement click
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btn.clearFocus();
            viewSwitcher.showNext();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(btn.getWindowToken(), 0);
            // Enregistre l'adresse.
            addAddress(view);
        }
    });

Regards.

Jean-Luc Barat
  • 1,147
  • 10
  • 18
1

You can also create a custom extension of the EditText that knows to open the soft keyboard when it receives focus. That's what I've ended up doing. Here's what worked for me:

public class WellBehavedEditText extends EditText {
    private InputMethodManager inputMethodManager;
    private boolean showKeyboard = false;

    public WellBehavedEditText(Context context) {
        super(context);
        this.initializeWellBehavedEditText(context);
    }

    public WellBehavedEditText(Context context, AttributeSet attributes) {
        super(context, attributes);
        this.initializeWellBehavedEditText(context);
    }

    public WellBehavedEditText(Context context, AttributeSet attributes, int defStyleAttr) {
        super(context, attributes, defStyleAttr);
        this.initializeWellBehavedEditText(context);
    }

    public WellBehavedEditText(Context context, AttributeSet attributes, int defStyleAttr, int defStyleRes) {
        super(context, attributes, defStyleAttr, defStyleRes);
        this.initializeWellBehavedEditText(context);
    }

    private void initializeWellBehavedEditText(Context context) {
        this.inputMethodManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);

        final WellBehavedEditText editText = this;
        this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(showKeyboard) {
                    showKeyboard = !(inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_FORCED));
                }
            }
        });
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(!focused) this.showKeyboard = false;
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
        boolean result = super.requestFocus(direction, previouslyFocusedRect);
        this.showKeyboard = true;
        final WellBehavedEditText self = this;
        this.post(new Runnable() {
            @Override
            public void run() {
                showKeyboard = !(inputMethodManager.showSoftInput(self, InputMethodManager.SHOW_FORCED));
            }
        });
        return result;
    }
}
SnoopDougg
  • 1,467
  • 2
  • 19
  • 35
  • Oh god at last, the `addOnGlobalLayoutListener` did the trick! I don't have to resort to ugly input hacks Thank you! I get a few warnings in the logs though – vctls Feb 04 '22 at 21:42
1

call requestFocus() method on editText in onCrete() method of activity() and call clearFocus() method on the same editText when click done in keypad.

Er Prajesh
  • 61
  • 1
  • 5
1

This is wild, but actually does work

fun showKeyboard(view: View) {
    try {
        InputMethodManager::class.java.getMethod(
                "showSoftInputUnchecked",
                Int::class.javaPrimitiveType,
                ResultReceiver::class.java
        ).apply {
            isAccessible = true
            invoke(view.context.inputMethodManager, 0, null)
        }
    }
    catch (e: Exception) {
       e.printStackTrace()
    }
}
jujka
  • 1,190
  • 13
  • 18
1

I use timer. Keyboard can show when edittext isfocused.

    edittext = (EditText) findViewById(R.id.edittext );
    edittext.requestFocus();
    edittext.setFocusableInTouchMode(true);
    if (edittext.requestFocus()) {
        final Thread timer = new Thread() {
            public void run() {
                try{
                    sleep(500);
                    InputMethodManager imm =(InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edittext, SHOW_IMPLICIT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        timer.start();
Cha Mildz
  • 11
  • 2
1

According to this answer I used the setSoftInputMode method and overrided theese methods in DialogFragment:

@Override
public void onCancel(@NonNull DialogInterface dialog) {
    super.onCancel(dialog);
    requireDialog().getWindow().setSoftInputMode(InputMethodManager.HIDE_IMPLICIT_ONLY);
}

@Override
public void onStart() {
    super.onStart();
    requireDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}

@Override
public void onStop() {
    super.onStop();
    requireDialog().getWindow().setSoftInputMode(InputMethodManager.HIDE_IMPLICIT_ONLY);
}

I also made my own subclass of DialogFragment with theese methods, so when you create another dialog and inherit from this class, you have the soft keyboard showed automatically without any other edits. Hope it will be useful for someone.

Vít Kapitola
  • 499
  • 1
  • 5
  • 9
1

to show keyboard forcefully use this code:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
Marium Jawed
  • 391
  • 4
  • 9
1

After trying every individual answer here the keyboard doesn't show up.. I got hours to get this solved, so hope someone doesn't waste it in the future..

For my case, the issue was not a programming issue at at, I was testing on an emulator with a phone that has a hardware keyboard, so it doesn't show up the software keyboard by default, to solve this, you need to make sure that the show soft input enabled in your emulator by turning off the hardware keyboard or enable the soft keyboard.

In faced this only on API-15 & 16. Here are screen shots how to do that

On Geny Motion emulator:

enter image description here enter image description here

On Android Studio emulator:

enter image description here

Zain
  • 37,492
  • 7
  • 60
  • 84
1

For kotlin extension use below.

fun EditText.toggle() {
   requestFocus()
   val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
   imm.showSoftInput(this, 0)
}

Access it by:

editText.toggle()
Arul
  • 1,031
  • 13
  • 23
0

Using Xamarin, this works for me inside a Fragment:

using Android.Views.InputMethods;
using Android.Content;

...

if ( _txtSearch.RequestFocus() ) {
  var inputManager = (InputMethodManager) Activity.GetSystemService( Context.InputMethodService );
  inputManager.ShowSoftInput( _txtSearch, ShowFlags.Implicit );
}
sprocket12
  • 5,368
  • 18
  • 64
  • 133
0

I made this help class. Just pass the context and the View you want to focus and show keyboard and after hide keyboard. I hope it Helps.

public class FocusKeyboardHelper {

private View view;
private Context context;
private InputMethodManager imm;

public FocusKeyboardHelper(Context context, View view){
    this.view = view;
    this.context = context;
    imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
}

public void focusAndShowKeyboard(){

    view.requestFocus();
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

}

public void hideKeyBoard(){
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

}

0
 void requestFocus(View editText, Activity activity)
{
    try {
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

add this line too do not forget

activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
saigopi.me
  • 14,011
  • 2
  • 83
  • 54
0

Worked for me after adding this lines.

globalSearchBarMainActivity.setEnabled(true);
globalSearchBarMainActivity.requestFocus();

As my auto complete text view method was hidden i.e. VISIBLE: GONE

So needed to add above two line

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(globalSearchBarMainActivity, InputMethodManager.SHOW_IMPLICIT);
rock123A
  • 82
  • 2
  • 11
0

view.requestFocus() might not work for diffrent reasons. So the Keyboard will not show.

A view will not actually take focus if it is not focusable (isFocusable returns false), or if it can't be focused due to other conditions (not focusable in touch mode (isFocusableInTouchMode) while the device is in touch mode, not visible, not enabled, or has no size).

I used this solution:

 @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
    EditText searchView = findViewById(R.id.searchView);
    
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            showSoftKeyboard(searchView);
        }
    }, 300);
}

public void showSoftKeyboard(View view) {
    if (view.requestFocus()) {
        InputMethodManager imm = (InputMethodManager)
                view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40