Android Clearing all EditText Fields with Clear Button

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.

🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)