115

I'm trying to set and onclicklistener so that when I click within the edittext element it will clear its current contents. Is there something wrong here? When I compile this code I get a force quit and ActivityManager: Can't dispatch DDM chunk 4d505251: no handler defined error.

public class Project extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    EditText editText = (EditText)findViewById(R.id.editText1);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        editText.setOnClickListener(this);

        setContentView(R.layout.main);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        editText.setText("");
    }
}
locoboy
  • 38,002
  • 70
  • 184
  • 260
  • Thanks all! Is there a reason that I have to declare it after? – locoboy Mar 15 '11 at 06:34
  • 2
    Yep! you have to call setContentView(id) first. So that the system can display the screen contents, and then you point out the EditText which will probably exist in your screen contents. Otherwise it will show an exception with Force Close dialog. – Adil Soomro Mar 15 '11 at 06:57
  • You can also achieve same functionality by setting the hint property of an edittext. You just have to set the text in hint property and same functionality will be achieved. – bhavindesai Mar 15 '11 at 06:27
  • You can't use `findViewById` until after you've called `setContentView`. – Ted Hopp Mar 15 '11 at 06:25
  • `EditText editText = (EditText)findViewById(R.id.editText1);` This line here should be placed inside the onCreate method. It is a function call by the context. – Some Noob Student Mar 15 '11 at 06:24
  • 1
    Move EditText editText = (EditText)findViewById(R.id.editText1); after setContentView(R.layout.main); – Diego Torres Milano Mar 15 '11 at 06:25
  • Please check that have you added this activity in your manifest file? – Rohit Mandiwal Mar 15 '11 at 06:25
  • 2
    Notice that you can set a "hint" to an `EditText`, which makes it display a text when empty and which disappears when the user starts typing. Add `android:hint="your hint text here"` to your `EditText` in xml. A 'hint' is usually used to indicate what the EditText is made for. It is maybe not what you're looking for, but I was also looking to clear the `EditText` on click until I discovered that the "hint" did what I was really looking for. – Jecimi Jul 05 '12 at 21:26

18 Answers18

232

Also you can use code below

editText.getText().clear();
Serhii Nadolynskyi
  • 5,473
  • 3
  • 21
  • 20
151

First you need to call setContentView(R.layout.main) then all other initialization.

Please try below Code.

public class Trackfolio extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    public EditText editText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        editText = (EditText) findViewById(R.id.editText1);
        editText.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        editText.getText().clear(); //or you can use editText.setText("");
    }
}
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • 6
    Hi, I know this is an old answer but you're the only one that mentions both options (`.clear` or `.setText("")`). Are there any differences? When should I use which one or are they completely the same? Thanks. – Alex Feb 15 '19 at 12:29
  • editText.getText().clear(); did nt work for mr in android studio 3.5.1 – Abdul Wahid Apr 22 '20 at 17:14
45

just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.

user2088464
  • 459
  • 4
  • 2
15

We can clear EditText data in two ways

First One setting EditText is empty like below line

editext.setText("");

Second one clearing EditText data like this

editText.getText().clear();

I suggest second way

Venki WAR
  • 1,997
  • 4
  • 25
  • 38
  • This is an old thread but I can't find a better one to post this. I have tried: – PeteC Mar 19 '21 at 18:45
  • This is an old thread but I can't find a better one to post this. I have tried the OnClick with edittext.setText("). When the user taps in the EditText any previous text is cleared and the keyboard pops up. I can type numbers but then when Ii tap done on the keyboard the numbers are cleared and the keyboard remains ready for more numbers. I can't get rid of the keyboard unless I restart the app – PeteC Mar 19 '21 at 18:52
  • _Why_ do you suggest the second way? How is it better? Please elaborate – Captain Jack Sparrow Jun 23 '22 at 20:27
8

Your code should be:

    public class Project extends Activity implements OnClickListener {
            /** Called when the activity is first created. */
            EditText editText;
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);            

                setContentView(R.layout.main);
                editText = (EditText)findViewById(R.id.editText1);
                editText.setOnClickListener(this);            
            }

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if(v == editText) {
                    editText.setText("");
                }
            }
        }
Anju
  • 9,379
  • 14
  • 55
  • 94
6

For Kotlin:

Create two extensions, one for EditText and one for TextView

EditText:

fun EditText.clear() { text.clear() }

TextView:

fun TextView.clear() { text = "" }

and use it like

myEditText.clear()

myTextView.clear()
MaKi
  • 263
  • 5
  • 11
4
public EditText editField;
public Button clear = null;
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
    setContentView(R.layout.text_layout);
   this. editField = (EditText)findViewById(R.id.userName);
this.clear = (Button) findViewById(R.id.clear_button);  
this.editField.setOnClickListener(this);
this.clear.setOnClickListener(this);
@Override
public void onClick(View v) {

    // TODO Auto-generated method stub
if(v.getId()==R.id.clear_button){
//setText will remove all text that is written by someone
    editField.setText("");
    }
}
Fakhar
  • 3,946
  • 39
  • 35
4

Very Simple to clear editText values.when u click button then only follow 1 line code.

Inside button or anywhere u want.Only use this

editText.setText("");   
Ashish Dwivedi
  • 8,048
  • 5
  • 58
  • 78
Guru
  • 186
  • 14
3

i don't know what mistakes i did while implementing the above solutions, bt they were unsuccessful for me

txtDeck.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override       
    public void onFocusChange(View v, boolean hasFocus) {
        txtDeck.setText("");
    }
});

This works for me,

Ziem
  • 6,579
  • 8
  • 53
  • 86
sailor
  • 753
  • 1
  • 6
  • 17
3
package com.example.sampleproject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class SampleProject extends Activity {
    EditText mSearchpeople;
    Button mCancel , msearchclose;
    ImageView mprofile, mContact, mcalender, mConnection, mGroup , mFollowup , msetting , mAddacard;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);
        mSearchpeople = (EditText)findViewById(R.id.editText1);
        mCancel = (Button)findViewById(R.id.button2);
        msearchclose = (Button)findViewById(R.id.button1);
        mprofile = (ImageView)findViewById(R.id.imageView1);
        mContact = (ImageView)findViewById(R.id.imageView2);
        mcalender = (ImageView)findViewById(R.id.imageView3);
        mConnection = (ImageView)findViewById(R.id.imageView4);
        mGroup = (ImageView)findViewById(R.id.imageView5);
        mFollowup = (ImageView)findViewById(R.id.imageView6);
        msetting = (ImageView)findViewById(R.id.imageView7);
        mAddacard = (ImageView)findViewById(R.id.imageView8);
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mSearchpeople.clearFocus();

            }
        });
    }


}
Madhu
  • 1,780
  • 23
  • 47
2

//To clear When Clear Button is Clicked

firstName = (EditText) findViewById(R.id.firstName);

    clear = (Button) findViewById(R.id.clearsearchSubmit);

    clear.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.clearsearchSubmit);
            firstName.setText("");
        }
    });

This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps

ashim888
  • 206
  • 10
  • 22
1
final EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);

childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        //Log.d("NNN", "Has focus " + hasFocus);
        if (hasFocus) {
            Toast.makeText(ctx.getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ctx.getApplicationContext(),
            "loss the focus", Toast.LENGTH_SHORT).show();
        }
        return;
    });
Pang
  • 9,564
  • 146
  • 81
  • 122
Nikhil
  • 23
  • 1
  • 6
1

by setting Empty string you can clear your edittext

    editext.setText("");
saigopi.me
  • 14,011
  • 2
  • 83
  • 54
1

If the use of EditText is not mandatory, you can implement this behavior easily with the new material components:

<com.google.android.material.textfield.TextInputLayout
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_field"
            app:endIconDrawable="@drawable/ic_close_black_24dp"
            app:endIconMode="clear_text"
            app:endIconTint="@color/black">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_value"
                android:maxLines="1"
                android:text="@{itemModel.value}" />

        </com.google.android.material.textfield.TextInputLayout>

You only have to specify the drawable you want for the button that will clear the text and the action that it will execute. To clear the text, you can use iconMode="clear_text", but also "password_toggle" is available.

Jesús Barrera
  • 400
  • 1
  • 5
  • 15
1

In XML you can write like:

    <EditText
        android:id="@+id/txtsearch"
        android:layout_width="250dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:layout_weight="1"
        android:background="@drawable/roundlayoutbutton1"
        android:ems="10"
        android:gravity="center"
        android:inputType="text"
        android:textAllCaps="true"
        android:text="search_xxxx"

        android:textColor="@color/colorPrimaryDark"
        android:visibility="visible" />

and in java class you may have below one :

    EditText searchHost;

OnCreate() you write:

    searchHost=findViewById(R.id.txtsearch);

    searchHost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(searchHost.getText().toString().equalsIgnoreCase("search_xxxx")){
                searchHost.setText("");
                Toast.makeText(getApplicationContext(),"Enter you text xxx...", Toast.LENGTH_LONG).show();
            }
        }
    });

It works fine for me.

Ashok
  • 61
  • 1
  • 2
0

You can use the 'android:hint' attribute in your EditText also from code:

editText.setHint(CharSequence hint / int resid);

Then you don't need any onClickListener or similar. But consider that the hint value won't be passed. The editText will be stayed empty. In this case you can set your editText with your deflault value:

if(editText.getText().toString().equals("")) { 
...use your default value instead of the editText... }
John
  • 1
  • 1
0

It's simple: declare the widget variables (editText, textView, button etc.) in class but initialize it in onCreate after setContentView.

The problem is when you try to access a widget of a layout first you have to declare the layout. Declaring the layout is setContentView. And when you initialize the widget variable via findViewById you are accessing the id of the widget in the main layout in the setContentView.

I hope you get it!

Sacha
  • 819
  • 9
  • 27
-1

I am not sure if your searching for this one

    {
    <EditText
     .
     . 
     android:hint="Please enter your name here">
    }
Mohamed Sajjadh
  • 139
  • 2
  • 11