Android 使用清除按钮清除所有 EditText 字段 [英] Android Clearing all EditText Fields with Clear Button

查看:52
本文介绍了Android 使用清除按钮清除所有 EditText 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Clear Button 清除布局中的所有 EditText 字段.我有一个注册活动,它有大约 10 个不同的 EditTexts.我知道我可以去获取每个特定的引用,然后 set.Text("");但我正在寻找一种更动态优雅的方式.可能会抓取 Layout 并遍历其中的所有项目以查找 EditText 类型,然后将它们设置为 "".不知道如何做到这一点,并尝试在网上搜索它,但没有运气.有示例代码吗?

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?

推荐答案

@Pixie 的回答很好,但我想让它变得更好.

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

只有当所有 EditText 都在一个(一个)布局中时,此方法才能正常工作,但是当有一堆嵌套布局时,此代码不会处理它们.

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));

您可以在哪里用您的 XML 文件的根布局的 ID 替换您的 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.

:)

这篇关于Android 使用清除按钮清除所有 EditText 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆