我如何清除布局的所有的EditText
字段与清除按钮
。我有一个注册活动,有大约10个不同的 EditTexts
。我知道我可以去抓住一个参考每个具体然后 set.Text()
;但是,我要寻找一个更具活力的优雅的方式。在所有的项目可能抢布局
和循环在那里找的EditText
类型,然后将这些设置为,
。不知道该怎么做,但并尝试在网上搜索了它,但没有运气上。任何样品code?
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都在单(一个)的布局,但如果有一堆嵌套布局这一code没有处理这些问题。
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.
:)