Search code examples
androidfocusandroid-edittext

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


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

Solution

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