如何使用 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字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
EditText:禁用文本选择处理程序单击事件上的粘贴EditText: Disable Paste/Replace menu pop-up on Text Selection Handler click event(EditText:禁用文本选择处理程序单击事件上的粘贴/替换菜
2.3 上带有完成 SoftInput 操作标签的多行 EditTextMultiline EditText with Done SoftInput Action Label on 2.3(2.3 上带有完成 SoftInput 操作标签的多行 EditText)
如何在 Android 中检测向左或向右滑动?How to detect the swipe left or Right in Android?(如何在 Android 中检测向左或向右滑动?)
防止在Android中的屏幕旋转对话框解除Prevent dialog dismissal on screen rotation in Android(防止在Android中的屏幕旋转对话框解除)
如何处理 ImeOptions 的完成按钮点击?How do I handle ImeOptions#39; done button click?(如何处理 ImeOptions 的完成按钮点击?)
您如何将 EditText 设置为仅接受 Android 中的数值How do you set EditText to only accept numeric values in Android?(您如何将 EditText 设置为仅接受 Android 中的数值?)