Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText clear text on first focus - Android [closed]

I have few EditText objects with text inside. I want that on the first time an EditText is getting focus to delete the text in it, but only on the first time.

How can i do it?

Here's an example: I have an EditText called SomeThing with the text "someText" in it. when the user touches SomeThing for the first time i want the "someText" to be deleted. so let's say the text was deleted and now the user typed in his own text, this time "someOtherText", and the EditText lost focus for some other EditText. This time when the user will tap SomeThing, "someOtherText" won't get deleted because that's the second time it get's focus.

like image 967
Matan Kadosh Avatar asked Oct 23 '12 01:10

Matan Kadosh


2 Answers

Matan, I am not sure if this is what you are looking at, but I think you want to display a 'hint' for your Edit Text

Example

<EditText
.
.
 android:hint="Please enter your name here">

For an example check this http://www.giantflyingsaucer.com/blog/wp-content/uploads/2010/08/android-edittext-example-3a.jpg

like image 191
Soham Avatar answered Nov 13 '22 13:11

Soham


If you are looking for a way to add placeholder for the EditText, just add android:hint = 'some text' to the corresponding XML file or call the setHint('some text') method on the EditText.

Otherwise, you can use the OnFocusChangeListener() to respond to the get focused event. To check if it is the first time for the EditText to get focused, use another Boolean variable (e.g., isFirstTimeGetFocused) and initialized it to true in onCreate() method. After the EditText gets focused, set isFirstTimeGetFocused to false;

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus && isFirstTimeGetFocused){
        editText.setText("");
        isFirstTimeGetFocused = false;
    }
});
like image 32
LazarusX Avatar answered Nov 13 '22 13:11

LazarusX