Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Clearing all EditText Fields with Clear Button

How do I clear all the EditText fields in a layout with a Clear Button. I have a registration Activity that has about 10 different EditTexts. I know I could go and grab a reference to each specifically and then set.Text(""); But I am looking for a more dynamic elegant way. Possibly grab the Layout and loop through all the items in there looking for EditText types and then setting those to "". Not sure how to do that though and tried searching on the web for it but no luck. Any sample code?

like image 917
JPM Avatar asked Apr 21 '11 07:04

JPM


People also ask

How to clear text in EditText Android on button click?

This will be possible using getText(). clear() method. This method will first get the already typed text from edittext and then clear it.

How do you delete text messages on an android?

Tap the conversation. Touch and hold the message you want to delete. Optional: To delete multiple messages, touch and hold the first message, then tap more messages. Tap Delete to confirm.

How do I use hint on Android?

To label an editable TextView or EditText , use android:hint to display a descriptive text label within the item when it's empty. If an app's user interface already provides a text label for the editable item, define android:labelFor on the labeling View to indicate which item the label describes.


2 Answers

The answer by @Pixie is great but I would like to make it much better.

This method works fine only if all the EditText are in a single(one) layout but when there are bunch of nested layouts this code doesn't deal with them.

After scratching my head a while I've made following solution:

private void clearForm(ViewGroup group) {            for (int i = 0, count = group.getChildCount(); i < count; ++i) {         View view = group.getChildAt(i);         if (view instanceof EditText) {             ((EditText)view).setText("");         }          if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))             clearForm((ViewGroup)view);     } } 

To use this method just call this in following fashion:

clearForm((ViewGroup) findViewById(R.id.sign_up)); 

Where you can replace your R.id.sign_up with the id of root layout of your XML file.

I hope this would help many people as like me.

:)

like image 58
necixy Avatar answered Sep 26 '22 08:09

necixy


You can iterate through all children in a view group and clear all the EditText fields:

ViewGroup group = (ViewGroup)findViewById(R.id.your_group); for (int i = 0, count = group.getChildCount(); i < count; ++i) {     View view = group.getChildAt(i);     if (view instanceof EditText) {         ((EditText)view).setText("");     } } 
like image 23
Michael Avatar answered Sep 23 '22 08:09

Michael