Tuesday, August 18, 2015

How to remove auto focus from EditText in Android

Remove Auto Focus From EditText
EditText is an Android SDK element that allows users to enter text and modify text in the app interface. But when developers put an EditText in the app interface by default it catches the focus. This call EditText auto focus behavior. This is sometimes annoying for android app users.

In this android app development tutorial, we demonstrate and describe how we can remove auto focus from an EditText in-app interface. To achieve this we have to apply a simple trick.

In the first step, we will create an XML layout file called the main activity layout file. Then we will put EditText there. We will wrap the EdiText with a relative layout element. Now we will put focus on the relative layout of the activity start. So, relative layout catches the focus on start instead EditText.

To put focus on relative layout we have to add two special attributes to the relative layout tag. One is ‘focusable’ and its value is true. Another attribute is ‘focusableInTouchMode’ and its value is also true. So, now our relative layout is focusable and it gets focused on touch. Finally, in this way, we will get an EditText without auto focus.
activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#d4c5b8"
    android:focusable="true"
    android:focusableInTouchMode="true"
    >
    <!--
        RelativeLayout
            android:focusable="true"
            android:focusableInTouchMode="true"

            This two attributes remove focus from both EditText
            widgets and set focus to layout container widget.
    -->
    <EditText
        android:id="@+id/et"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:hint="Input your country"
        android:padding="10dp"
        />
    <EditText
        android:id="@+id/et_city"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:hint="Input your City"
        android:padding="10dp"
        android:layout_below="@+id/et"
        />
</RelativeLayout>