user1065969 user1065969 - 6 months ago 19
Android Question

How to retain the hint text in android EditText field?

In my android app, I have a hint text in my EditText view. Once the user starts typing, I want the hint to be displayed on top of the edittext field. The original hint text disappears when user starts typing which is fine. How do I place a text on top of the edittext field ? Is there a way to make the EditText field multiline and use the first line for hint? But the user input should always start from the second line. enter image description here

Thanks in advance for your help!


Answer

You can use FloatLabelLayout. It's a custom component that works as described in the google documentation.

Once you create the custom component you can use it in this way:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <your.package.FloatLabelLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:floatLabelTextAppearance="@style/TextAppearance.YourApp.FloatLabel">

        <EditText
            android:id="@+id/edit_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/account_username_hint"
            android:singleLine="true"
            android:inputType="textNoSuggestions"
            android:imeOptions="actionNext"
            android:nextFocusDown="@+id/edit_password" />

    </your.package.FloatLabelLayout>

    <your.package.FloatLabelLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:floatLabelTextAppearance="@style/TextAppearance.YourApp.FloatLabel">

        <EditText
            android:id="@+id/edit_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/account_password_hint"
            android:singleLine="true"
            android:inputType="textNoSuggestions"
            android:imeOptions="actionDone" />

    </your.package.FloatLabelLayout>

</LinearLayout>