Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear an EditText on click?

In Android how can I make an EditText clear when it's clicked?

E.g., if I have an EditText with some characters in, such as 'Enter Name', when the user clicks on it these characters disappear.

like image 286
Entropy1024 Avatar asked Nov 13 '10 23:11

Entropy1024


Video Answer


2 Answers

I'm not sure if you are after this, but try this XML:

android:hint="Enter Name" 

It displays that text when the input field is empty, selected or unselected.

Or if you want it to do exactly as you described, assign a onClickListener on the editText and set it empty with setText().

like image 198
Specur Avatar answered Sep 20 '22 00:09

Specur


Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:

String value = "";//any text you are pre-filling in the EditText  final EditText et = new EditText(this); et.setText(value); final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight()); et.setCompoundDrawables(null, null, value.equals("") ? null : x, null); et.setOnTouchListener(new OnTouchListener() {     @Override     public boolean onTouch(View v, MotionEvent event) {         if (et.getCompoundDrawables()[2] == null) {             return false;         }         if (event.getAction() != MotionEvent.ACTION_UP) {             return false;         }         if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {             et.setText("");             et.setCompoundDrawables(null, null, null, null);         }         return false;     } }); et.addTextChangedListener(new TextWatcher() {     @Override     public void onTextChanged(CharSequence s, int start, int before, int count) {         et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);     }      @Override     public void afterTextChanged(Editable arg0) {     }      @Override     public void beforeTextChanged(CharSequence s, int start, int count, int after) {     } }); 
like image 26
Elijah Avatar answered Sep 20 '22 00:09

Elijah