Remove autofocus from an EditText in Android


SDK Version: 
M3

When we create a layout with an EditText or an AutoCompleteTextView, for some reason, it always gains the focus on starting.

focused

Here is the main.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical" android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent">
  5.         <Button android:text="@string/button_text"; android:id="@+id/Button01"
  6.                 android:layout_width="wrap_content" android:layout_height="wrap_content">
  7.         </Button>
  8.         <EditText android:text="" android:id="@+id/EditText01"
  9.                 android:layout_width="wrap_content" android:layout_height="wrap_content"
  10.                 android:hint="@string/hint">
  11.         </EditText>
  12.         <Button android:text="@string/button_text"; android:id="@+id/Button02"
  13.                 android:layout_width="wrap_content" android:layout_height="wrap_content">
  14.         </Button>
  15. </LinearLayout>

How can we remove the focus form the EditText, without giving it to an other visible layout element?
The simplest (and I think, the only 100% working) solution is, to create an invisible LinearLayout. This LinearLayout will grab the focus from the EditText.

Modify the main.xml like this, add a LinearLayout before the EditText:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical" android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent">
  5.         <Button android:text="@string/button_text"; android:id="@+id/Button01"
  6.                 android:layout_width="wrap_content" android:layout_height="wrap_content">
  7.         </Button>
  8.         <LinearLayout android:focusable="true"
  9.                 android:focusableInTouchMode="true" android:layout_width="0px"
  10.                 android:layout_height="0px" />
  11.         <EditText android:text="" android:id="@+id/EditText01"
  12.                 android:layout_width="wrap_content" android:layout_height="wrap_content"
  13.                 android:hint="@string/hint">
  14.         </EditText>
  15.         <Button android:text="@string/button_text"; android:id="@+id/Button02"
  16.                 android:layout_width="wrap_content" android:layout_height="wrap_content">
  17.         </Button>
  18. </LinearLayout>

focused

No other coding needed, it's a simple and clear solution.