How to stop EditText from gaining focus at Activity startup in Android

Mark picture Mark · Oct 12, 2009 · Viewed 758.1k times · Source

I have an Activity in Android, with two elements:

  1. EditText
  2. ListView

When my Activity starts, the EditText immediately has input focus (flashing cursor). I don't want any control to have input focus at startup. I tried:

EditText.setSelected(false);
EditText.setFocusable(false);

No luck. How can I convince the EditText to not select itself when the Activity starts?

Answer

Morgan Christiansson picture Morgan Christiansson · Nov 2, 2009

Excellent answers from Luc and Mark however a good code sample is missing. Adding the tag android:focusableInTouchMode="true" and android:focusable="true" to parent layout (e.g. LinearLayout or ConstraintLayout) like the following example will fix the problem.

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:focusable="true" 
    android:focusableInTouchMode="true"
    android:layout_width="0px" 
    android:layout_height="0px"/>

<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="@+id/autotext"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:nextFocusUp="@id/autotext" 
    android:nextFocusLeft="@id/autotext"/>