133

I have an activity with no child widgets for it and the corresponding xml file is,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"
>
</LinearLayout>

and I want to open soft keyboard programmatically while the activity gets start.and what I've tried upto now is,

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }

Give me some guidance.

NightFury
  • 13,436
  • 6
  • 71
  • 120
Vignesh
  • 3,571
  • 6
  • 28
  • 44
  • hi vignesh but what is the need to open soft keyboard without any textView? – milind Apr 08 '11 at 09:24
  • Actually I'm trying to use key listener in that activity, for that I need to do so. – Vignesh Apr 08 '11 at 09:29
  • What you have done is correct. I am not sure why you are not seeing the keyboard. I used this code once to launch the keyboard without any user action on a editText and it was successful. – Vinoth Apr 08 '11 at 11:15
  • Hi Vinoth, I've changed my code as exactly as DSouza posts and I've updated in my question too, so check is there anything I've to change. – Vignesh Apr 08 '11 at 11:59

29 Answers29

157

I have used the following lines to display the soft keyboard manually inside the onclick event, and the keyboard is visible.

InputMethodManager inputMethodManager =
    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
    linearLayout.getApplicationWindowToken(),
    InputMethodManager.SHOW_FORCED, 0);

But I'm still not able to open this while the activity gets opened, so are there any solution for this?

omerfarukdogan
  • 839
  • 9
  • 26
Vignesh
  • 3,571
  • 6
  • 28
  • 44
  • @YosiTaguri, much more elegant if you are dealing with activities. And what about fragments ?! +1 for both answers – S.Thiongane Feb 19 '14 at 15:07
  • and what if you have to open keyboard on dialog having edit text? How to do that? – seema May 14 '14 at 08:02
  • 7
    @Vignesh : you need to give some delay like 500 milliseconds while opening the keyboard if you want to implement this code at time of launching the activity. – Vinit Saxena Jun 19 '16 at 14:09
  • @vinitsaxena Thank you for your valuable comment – Vignesh Jun 20 '16 at 11:19
  • i am not sure but i was try get any view for example TextView and append listener like this myTextView.post(new Runnable() { public void run() { //here your method } }); and when this view will create it means that all screen visible now you can call whatever you want – Sirop4ik Jun 28 '16 at 12:15
130

In your manifest file, try adding the following to the <activity> that you want to show the keyboard when the activity starts:

android:windowSoftInputMode="stateVisible"

This should cause the keyboard to become visible when the activity starts.

For more options, checkout the documentation.

jemerick
  • 1,518
  • 1
  • 10
  • 4
  • 5
    Wish I could upvote more often for this answer just to get all those dirty hacks to the bottom of the page ;) – fjdumont May 08 '12 at 17:47
  • 1
    How do you do this programatically? I only want the keyboard to automatically show in certain situations. – phreakhead Jan 03 '13 at 21:56
  • 1
    i have input dialog like this link [link](http://www.mkyong.com/android/android-prompt-user-input-dialog-example/) how to show keyboard not on activity but on prompt? this did work thank InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } – shareef May 11 '13 at 18:13
  • 10
    He says "programmatically". – Mert Akcakaya Aug 07 '13 at 06:54
  • 2
    It doesn't work for me. Instead, this does: android:windowSoftInputMode="stateAlwaysVisible" – Rendicahya Oct 24 '13 at 16:28
  • works well - particularly if you know that a screen will always need (or not need) a keyboard – Shaun Neal Jan 13 '14 at 18:51
  • Awesome answer. I was weary of the answers that say to use a runnable with a 300 MS timeout to constantly request focus. – JakeWilson801 Apr 18 '16 at 20:20
39

Please follow the below code. I am sure your problem will be solved.

if (imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
   } 
NightFury
  • 13,436
  • 6
  • 71
  • 120
AndroidDanger
  • 1,049
  • 1
  • 9
  • 17
  • Hi I just pasted your code inside onCreate function but still there is no change in my activity, if you want me to paste the code, I'll paste in comment. – Vignesh Apr 11 '11 at 07:16
  • When you want to access the softkeyboard please tell me so that i resolve your problem. Please send me code.... if possible – AndroidDanger Apr 11 '11 at 07:37
  • I want to set onKeyboardActionListener for my activity which has nothing other than linear layout. – Vignesh Apr 11 '11 at 07:43
  • Just see my question above in which I have edited the code with what you have provided for me. – Vignesh Apr 11 '11 at 07:48
  • This activity is only for keyboard action, I want to listen to each key pressed (using onKeyboardActionListener)and I'll pass it to the local server simultaneously – Vignesh Apr 11 '11 at 08:10
  • I know I'm three years late, but I've found this solution is correct if you use it inside the onCreateView method. – cbuchart Feb 14 '14 at 15:08
29

This is works

<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

or

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
ahtartam
  • 879
  • 9
  • 13
20

All I needed was to expose the keyboard, in a very precise moment. This worked for me! Thanks Benites.

    private Handler mHandler= new Handler();

And in the very precise moment:

    mHandler.post(
    new Runnable() {
        public void run() {
            InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
            yourEditText.requestFocus();
        }
    }); 
Diego Soto
  • 375
  • 3
  • 8
  • This solution worked for me inside onResume() with a slight modification on delaying the post action: `postDelayed( runnable, 500 /* msec */ );` – AVIDeveloper Nov 23 '13 at 22:41
  • 1
    I would recommend putting it in a ViewTreeObserver callback so it gets called on the first layout to avoid having to wait for an arbitrary amount of time. It should be safer/more responsive. – Gabriel Apr 17 '15 at 17:44
  • Only this solution worked for me. I had previous methods before which worked but unfortunately for the latest OS, The handler is the workable solution. – MD. Shafiul Alam Biplob Dec 25 '19 at 20:35
17

I have used the following lines to display the soft keyboard manually inside the onclick event.

public void showKeyboard(final EmojiconEditText ettext){
          ettext.requestFocus();
          ettext.postDelayed(new Runnable(){
            @Override public void run(){
              InputMethodManager keyboard=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
              keyboard.showSoftInput(ettext,0);
            }
          }
        ,200);
        }
Ram
  • 1,408
  • 13
  • 29
  • 1
    I was struggling with this for hours. Luckily your solution works great! Thanks for sharing! – Nick Jan 26 '21 at 16:50
15

Kotlin

fun hideKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Java

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
12

Put that in onResume method:

findViewById(R.id.root_view_of_your_activity_layout).post(
new Runnable() {
    public void run() {
        InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(),     InputMethodManager.SHOW_FORCED, 0);
        yourEditText.requestFocus();
    }
});

the runnable is needed because when the OS fires the onResume method you can't be sure that all the views where draw, so the post method called from your root layout makes it wait till every view is ready.

Marcelo Benites
  • 833
  • 8
  • 18
  • 1
    I had a SearchView in a DialogFragment and the first time the Dialog came up the SearchView had focus... but the keyboard was NOT up unless the user touched it. We had trying to just use showSoftInput and also toggleSoftInputFromWindow from the OnResume ALONE... or even in the OnFocusChangeListener for the SearchView... but none of those worked because they seemed to fire before the window was up and drawn......using this post event in the OnResume finally solved it. – lepert Sep 16 '13 at 20:52
  • i had a custom edittext in it's `onAttachedToWindow()` method i just called `requestFocus()` it worked in dialog fragment same thing didn't work in normal fragment couldn't understand why? – Abhinav Chauhan May 29 '21 at 10:40
10

in onCreate method of activity or onActivityCreated of a fragment

....
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            view.removeOnPreDrawListener(this);
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

            // !Pay attention to return `true`
            // Chet Haase told to 
            return true;
        }
    });
Alex
  • 1,416
  • 1
  • 14
  • 24
9

seems like this is working

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patientid);

        editText = (EditText)findViewById(R.id.selectPatient);
        //editText.requestFocus(); //works without that

    }

@Override
    protected void onResume() {

        findViewById(R.id.selectPatient).postDelayed(
        new Runnable() {
            public void run() {
                 editText.requestFocus();
                InputMethodManager inputMethodManager =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(editText,InputMethodManager.SHOW_IMPLICIT);
            }
        },100);
        super.onResume();
    }

seems this works better: in manifest:

<application>
    <activity
        android:name="com.doodkin.myapp.ReportActivity"
        android:label="@string/title_activity_report"
        android:screenOrientation="sensor" 
        android:windowSoftInputMode="stateHidden" > // add this or stateVisible
    </activity>
</application>

seems the manifest working in android 4.2.2 but not working in android 4.0.3

aimiliano
  • 1,105
  • 2
  • 12
  • 18
Shimon Doodkin
  • 4,310
  • 34
  • 37
9

I used it as singleton like:

public static void showSoftKeyboard(final Context context, final EditText editText) {
        try {
            editText.requestFocus();
            editText.postDelayed(
                    new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                            keyboard.showSoftInput(editText, 0);
                        }
                    }
                    , 200);
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Use it in your activity like:

showSoftKeyboard(this, yourEditTextToFocus);
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
8

I have used like this to show the soft keyboard programatically and this is worked for me to prevent the auto resize of the screen while launching the keyboard.

In manifest:

<activity android:name="XXXActivity" android:windowSoftInputMode="adjustPan">
</activity>

In XXXActvity:

EditText et =  (EditText))findViewById(R.id.edit_text);  
  Timer timer = new Timer();
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                    InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInputFromWindow(et.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);

                }
            };
            timer.schedule(task, 200);

I assume this will save others time to search for this problem.

Noundla Sandeep
  • 3,334
  • 5
  • 29
  • 56
5
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
Kai Wang
  • 3,303
  • 1
  • 31
  • 27
5

This works:

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

And you call this method like this:

showKeyboard(NameOfActivity.this);
Thiago Silva
  • 670
  • 6
  • 18
4
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Use above code in onResume() to open soft Keyboard

Sanket Parchande
  • 894
  • 9
  • 14
4

InputMethodManager.SHOW_FORCED isn't good choice. If you use this setting you should manage hiding keyboard state. My suggestion is like this;

    public void showSoftKeyboard(View view) {
    InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
    view.requestFocus();
    inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}

Also, you can focus on view (usually EditText) taking parameters it. This makes it a more useful function

for more info about InputMethodManager.SHOW_IMPLICIT and SHOW_FORCED; InputMethodManager

Cafer Mert Ceyhan
  • 1,640
  • 1
  • 13
  • 17
4
public final class AAUtilKeyboard {

public static void openKeyboard(final Activity activity, final EditText editText) {
    final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
}

public static void hideKeyboard(final Activity activity) {
    final View view = activity.getCurrentFocus();
    if (view != null) {
        final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}
Arsen
  • 71
  • 5
4
import androidx.core.view.WindowInsetsCompat.Type
import androidx.core.view.WindowInsetsControllerCompat

fun Activity.openKeyboard() {
    WindowInsetsControllerCompat(window, window.decorView).show(Type.ime())
}

fun Activity.hideKeyboard() {
    WindowInsetsControllerCompat(window, window.decorView).hide(Type.ime())
}
Philipp E.
  • 3,296
  • 3
  • 34
  • 52
Tatsuya Fujisaki
  • 1,434
  • 15
  • 18
3

Similar to the answer of @ShimonDoodkin this is what I did in a fragment.

https://stackoverflow.com/a/29229865/2413303

    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.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);
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
3

There are already too many answers but nothing worked for me apart from this

inputMethodManager.showSoftInput(emailET,InputMethodManager.SHOW_FORCED);

I used showSoftInput with SHOW_FORCED

And my activity has

 android:windowSoftInputMode="stateVisible|adjustResize"

hope this helps someone

spaceMonkey
  • 4,475
  • 4
  • 26
  • 34
3

perfectly working code to show and hide softkeyboard for edittextbox.....

// code to hide soft keyboard
public void hideSoftKeyBoard(EditText editBox) {
     InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
     imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0);  
}




// code to show soft keyboard
private void showSoftKeyBoard(EditText editBox){
     InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
     editBox.requestFocus();
     inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
Vishist Varugeese
  • 1,500
  • 1
  • 17
  • 30
YESVGO JOBS
  • 31
  • 1
  • 2
3

Based on above answers like this it works in KOTLIN as long as you have the context.

fun Context.showKeyboard(editText: EditText) {

    editText.requestFocus()
    editText.setSelection(editText.text.length)

    GlobalScope.launch {
        delay(200L)

        val inputMethodManager: InputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInputFromWindow(
            editText.applicationWindowToken,
            InputMethodManager.SHOW_IMPLICIT, 0
        )
    }
}

Then you can call it in your fragment for example as follows

requireContext().showKeyboard(binding.myEditText)

F.Mysir
  • 2,838
  • 28
  • 39
2

This is the required source code :

public static void openKeypad(final Context context, final View v) 
 {
new Handler().postDelayed(new Runnable() 
{
    @Override
    public void run() 
    {
        InputMethodManager inputManager =   (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); 
        inputManager.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);    
        Log.e("openKeypad", "Inside Handler");
    }
},300);}

For details , Please go through this link. This helped me. https://github.com/Nikhillosalka/Keyboard/blob/master/README.md

2

Post this method in your base activity and use it other activities like a charm

public void openKeyboard() {
    InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }
}
Ajay Chauhan
  • 1,471
  • 4
  • 17
  • 37
2

I like to do it as an extension to Context so you can call it anywhere

fun Context.showKeyboard(editText: EditText) {
    val inputMethodManager: InputMethodManager =
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.toggleSoftInputFromWindow(
        editText.applicationWindowToken,
        InputMethodManager.SHOW_IMPLICIT, 0
    )
    editText.requestFocus()
    editText.setSelection(editText.text.length)
}

fun Context.hideKeyboard(editText: EditText) {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(editText.windowToken, 0)
}
Sean Calkins
  • 312
  • 2
  • 11
2

In the Kotlin, you can use the below extension functions to show and hide the soft keyboard.

/**
  * Extension method to provide show keyboard for [Activity].
 */
fun Activity.showSoftKeyboard() {
  if (currentFocus != null) {
    val inputMethodManager =
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 inputMethodManager.showSoftInput(this.currentFocus,InputMethodManager.SHOW_IMPLICIT)
   } 
}


/**
 * Extension method to provide hide keyboard for [Activity].
 */
fun Activity.hideSoftKeyboard() {
   if (currentFocus != null) {
      val inputMethodManager =
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
    }
 }

That's all! Cheers!

Prateek
  • 502
  • 5
  • 16
1

If you want the keyboard to be up along with the activity/fragment launch, you can use the below code.

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputMethodManager =
                        (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.toggleSoftInputFromWindow(
                        etPhoneNumber.getApplicationWindowToken(),
                        InputMethodManager.SHOW_FORCED, 0);
            }
        }, 500);
Shubham Goel
  • 1,962
  • 17
  • 25
0

Best way to open Keyboard is to call the below kotlin code:

val inputMethodManager: InputMethodManager =
    getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager

inputMethodManager.showSoftInput(editText, 2)
QED
  • 9,803
  • 7
  • 50
  • 87
Rahul Jadhav
  • 41
  • 1
  • 4
0

Try use this:

    fun closeKeyboard(view: View) {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow(view.windowToken, HIDE_IMPLICIT_ONLY)
}

fun showKeyBoard(view: View) {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(
        view,
        SHOW_IMPLICIT
    )
}

And if not work, try wrap func in a run block like this:

  view.postDelayed({showKeyBoard(view)},100)