Android Clearing all EditText Fields with Clear Button(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));
您可以在其中将您的 R.id.sign_up 替换为您的 XML 文件的根布局的 id.
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字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android使用清除按钮清除所有EditText字段
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01