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

AndroidFocusAndroid Edittext

Android Problem Overview


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

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

use:

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

Solution 3 - Android

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

Solution 4 - Android

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

Solution 5 - Android

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!

Solution 6 - Android

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

Solution 7 - Android

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

Solution 8 - Android

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

}

Solution 9 - Android

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)

Solution 10 - Android

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)

Solution 11 - Android

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

Solution 12 - Android

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

Solution 13 - Android

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)

Solution 14 - Android

I know this is a late reply, but for people who are like me looking to do this in 2022, to find out that toggleSoftInput is deprecated (as of level 31), here is the new approach using showSoftInput:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
editView.requestFocus();
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                        .showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);

I tried the toggleSoftInput but found some issues, like the keyboard stays when I press the home button,but this approach worked for me perfectly.

Solution 15 - Android

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

}

Solution 16 - Android

In "OnCreate" move the cursor to the input field, but the keyboard will not open:

window().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
)
editText.requestFocus()

After that, while the user enters the text:

val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
window.setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
)
imm.showSoftInput(editText, 0)

will work adequately and the keyboard will open when needed without setting time delays. Remember, after entering the text, you must:

window.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
)
requestFocus()

Solution 17 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHoucineView Question on Stackoverflow
Solution 1 - AndroidDavid MerrimanView Answer on Stackoverflow
Solution 2 - AndroidungalcrysView Answer on Stackoverflow
Solution 3 - AndroidDanilo RaspaView Answer on Stackoverflow
Solution 4 - AndroidKunal BhatiaView Answer on Stackoverflow
Solution 5 - AndroidvincebodiView Answer on Stackoverflow
Solution 6 - AndroidalvarlagerlofView Answer on Stackoverflow
Solution 7 - AndroidHamza KhanView Answer on Stackoverflow
Solution 8 - AndroidPaul SpiesbergerView Answer on Stackoverflow
Solution 9 - AndroidsunnyView Answer on Stackoverflow
Solution 10 - AndroidveeyikpongView Answer on Stackoverflow
Solution 11 - AndroidVasudevView Answer on Stackoverflow
Solution 12 - AndroidHadi NoteView Answer on Stackoverflow
Solution 13 - AndroidLeFroschView Answer on Stackoverflow
Solution 14 - AndroidMohcine BAADIView Answer on Stackoverflow
Solution 15 - AndroidAndrew ChelixView Answer on Stackoverflow
Solution 16 - AndroidАнтон СавосинView Answer on Stackoverflow
Solution 17 - AndroidmwuView Answer on Stackoverflow