Tuesday, March 16, 2010

Default text for an EditText? Here's a Hint

Sometimes it can be a nice idea to put default values in an EditText to let your users know what sort of information you're wanting them to enter.

What I had been doing previously was setting the .text value of the EditText to some default value, then clearing it onClick, after checking if the value was still the default, like this:

etName.setOnClickListener(new OnClickListener() {

String name = etName.getText().toString();
String origVal = getResources().getText(R.string.NameDefault).toString();

public void onClick(View v) {



Here's my String resource, stored in res/strings.xml as used above:

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

<string name="NameDefault">Enter your name</string>

But there is another, easier way, and it's called a Hint.

Simply by adding the below, bold attribute into my xml layout, my EditText by default contains a default string, which only exists when the EditText is empty.

It's all done for me!

.. here is my layout xml, note the android:hint line:

<EditText android:id="@+id/etName"