211

I have a layout which contains some views like this:

<LinearLayout>
<TextView...>
<TextView...>
<ImageView ...>
<EditText...>
<Button...>
</linearLayout>

How can I set the focus (display the keyboard) on my EditText programmatically?

I've tried this and it works only when I launch my Activity normally, but when I launch it in a TabHost, it doesn't work.

txtSearch.setFocusableInTouchMode(true);
txtSearch.setFocusable(true);
txtSearch.requestFocus();
dkmann
  • 559
  • 2
  • 6
  • 17
Houcine
  • 22,593
  • 13
  • 53
  • 83
  • http://www.android-ios-tutorials.com/93/android-show-hide-soft-keyboard-programmatically/ – Houcine Feb 05 '14 at 09:11
  • Possible duplicate of [How to show soft-keyboard when edittext is focused](http://stackoverflow.com/questions/5105354/how-to-show-soft-keyboard-when-edittext-is-focused) – raukodraug May 20 '17 at 22:05

15 Answers15

392

Try this:

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

http://developer.android.com/reference/android/view/View.html#requestFocus()

Rafael Ruiz Muñoz
  • 4,769
  • 6
  • 41
  • 79
David Merriman
  • 5,633
  • 1
  • 16
  • 18
  • Updated with code to force the keyboard to show from this answer: http://stackoverflow.com/questions/5105354/how-to-show-soft-keyboard-when-edittext-is-focused – David Merriman Jan 24 '12 at 18:10
  • 5
    it works only when i launch my activity normally , but when i launch my activity on a TabHost , it doesn't work , – Houcine Jan 24 '12 at 18:23
  • How are you setting up your TabHost? – David Merriman Jan 24 '12 at 18:32
  • @Sharmilee : yes, i've changed the TabActivity to FragmentActivity and it works using the code above. To show or hide keyboard programmatically , you can see this tutorial :http://bit.ly/1kCmP9s – Houcine Jun 06 '14 at 11:37
  • 32
    This doesnt work. This one works for me InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); – Günay Gültekin Jan 24 '16 at 12:38
  • 7
    "This doesn't work brother". In some cases you need to call this code asynchronously from postDelayed(). I had a case when I had to open keyboard after user pressed "OK" on the dialog. And when dialog was closing it was messing with the focus. So I've called the code above from postDelayed(). It executed after dialog had closed. Profit. – Danylo Volokh Dec 12 '16 at 12:56
  • but this method open up keyboard forcefully, and even when we close app via home button, keyboard will be there. – Minkoo Nov 14 '17 at 05:59
  • 2
    237 up votes on the answer and 62 on "it doesn't work brother" I tested it to get own opinion and it works perfect!) – Daniel Jul 18 '18 at 13:10
  • What is **Context**? – Hamid Shafie Asl Oct 31 '18 at 09:09
  • I don't know why "This doesn't work brother" get so many upvote.. But it works for me – zihadrizkyef Jun 16 '19 at 10:04
  • @Minkoo, no, this method works well with Home button. But `InputMethodManager.SHOW_FORCED` solution really has a bug with Home button. – CoolMind Jul 02 '19 at 09:52
  • @zihadrizkyef, this method sometimes doesn't work. In TabHost, AlertDialog and in onCreateView. See https://stackoverflow.com/a/52663774/2914140. – CoolMind Jul 02 '19 at 09:58
  • 1
    Just to share the experience: I just added the code to four different fragments within my current app project. With the first three fragments the code worked flawlessly. With the last fragment no keyboard was shown until I started the code from onViewCreated with a 100ms delay using Kotlin Coroutines. – Nantoka Sep 05 '19 at 14:40
  • 1
    Addendum: I found another fragment where I needed the 100ms delay plus a view.clearFocus() before executing the code. – Nantoka Sep 05 '19 at 16:34
176

use:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
ungalcrys
  • 4,558
  • 2
  • 35
  • 22
56

This worked for me, Thanks to ungalcrys

Show keyboard:

editText = (EditText)findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);

Hide keyboard:

InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
Community
  • 1
  • 1
Danilo Raspa
  • 717
  • 5
  • 5
45
final EditText tb = new EditText(this);
tb.requestFocus();
tb.postDelayed(new Runnable() {
    @Override
    public void run() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(tb, InputMethodManager.SHOW_IMPLICIT);
    }
}, 1000);
Kunal Bhatia
  • 601
  • 5
  • 10
  • 1
    I had to do this in order to get it showing up in onResume(). Without the delay, nothing would happen using every single solution described in this thread. – FranticRock Dec 13 '16 at 18:17
  • 1
    There it is. That was the answer I was looking for. Though, you don't necesarily need an entire second delay. I tried just 150 millis, and that worked fine as well. – Rubberduck Jul 17 '17 at 12:10
  • 4
    Thanks! This works even for 0 ms (`tb.post({ showKeyboard(tb) })`). Notice that we need a EditText view (`tb`), not a fragment view. – CoolMind Jul 01 '19 at 15:33
41

showSoftInput was not working for me at all.

I figured I needed to set the input mode : android:windowSoftInputMode="stateVisible" (here in the Activity component in the manifest)

Hope this help!

Houcine
  • 22,593
  • 13
  • 53
  • 83
vincebodi
  • 517
  • 5
  • 3
27

Here is how a kotlin extension for showing and hiding the soft keyboard can be made:

fun View.showKeyboard() {
  this.requestFocus()
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

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

Then you can just do this:

editText.showKeyboard()
// OR
editText.hideKeyboard()
alvarlagerlof
  • 1,246
  • 1
  • 14
  • 26
6

Here is KeyboardHelper Class for hiding and showing keyboard

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by khanhamza on 06-Mar-17.
 */

public class KeyboardHelper {
public static void hideSoftKeyboard(final Context context, final View view) {
    if (context == null) {
        return;
    }
    view.requestFocus();
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}, 1000);
}

public static void hideSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}, 1000);
}


public static void openSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, 1000);
}
}
statosdotcom
  • 3,041
  • 2
  • 14
  • 35
Hamza Khan
  • 1,106
  • 7
  • 15
6

I recommend using a LifecycleObserver which is part of the Handling Lifecycles with Lifecycle-Aware Components of Android Jetpack.

I want to open and close the Keyboard when the Fragment/Activity appears. Firstly, define two extension functions for the EditText. You can put them anywhere in your project:

fun EditText.showKeyboard() {
    requestFocus()
    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)
}

Then define a LifecycleObserver which opens and closes the keyboard when the Activity/Fragment reaches onResume() or onPause:

class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
    LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun openKeyboard() {
        editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun closeKeyboard() {
        editText.get()?.hideKeyboard()
    }
}

Then add the following line to any of your Fragments/Activities, you can reuse the LifecycleObserver any times. E.g. for a Fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    // inflate the Fragment layout

    lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))

    // do other stuff and return the view

}
Paul Spiesberger
  • 4,334
  • 1
  • 37
  • 47
2

I tried a lot ways and it's not working tho, not sure is it because i'm using shared transition from fragment to activity containing the edit text.

Btw my edittext is also wrapped in LinearLayout.

I added a slight delay to request focus and below code worked for me: (Kotlin)

 et_search.postDelayed({
     editText.requestFocus()

     showKeyboard()
 },400) //only 400 is working fine, even 300 / 350, the cursor is not showing

showKeyboard()

 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
veeyikpong
  • 690
  • 7
  • 19
1

First way:

    etPassword.post(() -> {
        etPassword.requestFocus();
        InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.showSoftInput(etPassword, InputMethodManager.SHOW_IMPLICIT);
    });

Second way:

In Manifest:

    <activity
        android:name=".activities.LoginActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateVisible"/>

In code:

etPassword.requestFocus();
Hadi Note
  • 1,164
  • 12
  • 14
1
editTxt.setOnFocusChangeListener { v, hasFocus ->
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (hasFocus) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
            } else {
                imm.hideSoftInputFromWindow(v.windowToken, 0)
            }
        }
Vasudev
  • 1,318
  • 12
  • 14
1

I tried the top answer by David Merriman and it also didn't work in my case. But I found the suggestion to run this code delayed here and it works like a charm.

val editText = view.findViewById<View>(R.id.settings_input_text)

editText.postDelayed({
    editText.requestFocus()

    val imm = context.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}, 100)
LeFrosch
  • 37
  • 8
1

Put this into onResume() method.

binding.etxtSearch.isFocusableInTouchMode = true
binding.etxtSearch.isFocusable = true
binding.etxtSearch.requestFocus() 
val inputMethodManager = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(binding.etxtSearch, InputMethodManager.SHOW_IMPLICIT)
AgentP
  • 3,133
  • 2
  • 15
  • 27
sunny
  • 11
  • 3
0

I finally figured out a solution and create a Kotlin class for it

object KeyboardUtils {

    fun showKeyboard(editText: EditText) {
        editText.requestFocus()
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, 0)
    }

    fun hideKeyboard(editText: EditText) {
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
    }

}
Andrew Chelix
  • 413
  • 2
  • 9
-1

I couldn't get any of these answers to work on their own. The solution for me was to combine them:

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

I'm not sure why that was required for me -- according to the docs it seems that either method should have worked on their own.

mwu
  • 474
  • 6
  • 13
  • This is definitely not a good practice. Perhaps, Activity or Fragment transaction was intervening with the soft keyboard or the Input Method flags were not set correctly but either way, this solution should not be used. – Marcel Bro Nov 14 '18 at 12:17