問題描述
如何使用 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模板網!