Wednesday, August 19, 2015

How to add placeholder to an EditText in Android

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="#deeae5"
    >
    <!--
        android:hint
            Hint text to display when the text is empty.

            Must be a string value, using '\\;' to escape characters
            such as '\\n' or '\\uxxxx' for a unicode character.

            This may also be a reference to a resource (in the form
            "@[package:]type:name") or theme attribute (in the form
            "?[package:][type:]name") containing a value of this type.

            Sometimes android developers describe the hint as a placeholder.
    -->
    <EditText
        android:id="@+id/et"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:hint="Hint from xml layout file"
        />
    <EditText
        android:id="@+id/et2"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_below="@+id/et"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.widget.EditText;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        EditText et = (EditText) findViewById(R.id.et);
        EditText et2 = (EditText) findViewById(R.id.et2);

        /*
            setHint (CharSequence hint)
                Sets the text to be displayed when the text of the
                TextView is empty. Null means to use the normal empty
                text. The hint does not currently participate
                in determining the size of the view.
         */
        // Set the initial instructional text of third EditText
        // Set hint of the third EditText
        // Set the placeholder (hint) for second EditText
        et2.setHint("Hint (Placeholder) created programmatically");
    }
}
More android examples