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();

@Override
public void onClick(View v) {
if(name.equals(origVal));
{
etName.setText("");

}

}
});


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

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

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


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"
android:hint="@string/NameDefault"
android:minWidth="100dip"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</EditText>



8 comments:

  1. thx for the hint tip!


    tomig
    www.tomig.at

    ReplyDelete
  2. This helped me a bunch. Thank you!

    ReplyDelete
  3. that what i'm looking for, Thanks you :)

    ReplyDelete
  4. Thanks for the tip especially "Hint". :)

    ReplyDelete
  5. wow really good work thank you
    time saver!!

    ReplyDelete
  6. thanks dude...xml trick is so simple

    ReplyDelete