Android用清除按钮清除所有EditText字段(Android Clearing all EditText Fields with Clear Button)

编程入门 行业动态 更新时间:2024-10-28 22:23:38
Android用清除按钮清除所有EditText字段(Android Clearing all EditText Fields with Clear Button)

如何使用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的答案是非常好的,但我想让它更好。

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

在抓住我的头后,我做了以下解决方案:

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

要使用这种方法,请按以下方式调用:

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

您可以将您的R.id.sign_up替换为XML文件的根布局的ID。

我希望这可以帮助许多人像我一样。

:)

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.

:)

更多推荐

本文发布于:2023-08-07 18:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465477.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   按钮   EditText   Android   Button

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!