如何使用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.
:)
更多推荐
发布评论