我已经查看了有关此问题的其他问题,但解决方案对我不起作用。我在页面上有许多edittext字段,希望能够通过一键按下来重置它们。我实现了this thread的解决方案,但是我已经嵌套了线性布局,它只清除了作为主容器直接子代的edittext。我怎样才能找到所有的edittext字段,或者我必须引用每个字段?
我的xml文件结构如下:
<ScrollView>
<LinearLayout android:id="@+id/MainParent">
<LinearLayout>
TextView
EditText
</LinearLayout>
<LinearLayout>
TextView
EditText
</LinearLayout>
<LinearLayout>
TextView
EditText
</LinearLayout>
EditText
<LinearLayout>
Button1
Button2
</LinearLayout>
</LinearLayout>
</ScrollView>
来自Java文件的片段:
ViewGroup group = (ViewGroup)findViewById(R.id.MainParent);
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
答案 0 :(得分:4)
如果您对具体引用每个EditText不感兴趣,我会创建一个递归函数来处理层次结构。
public void clearAll(ViewGroup root) {
for (int i = 0, j = root.getChildCount(); i < j, i++) {
View view = root.getChildAt(i);
if (view instanceof ViewGroup) {
clearAll((ViewGroup) view);
continue;
}
if (view instanceof EditText) {
((EditText) view).setText("");
continue;
}
}
}
然后你打电话:
clearAll((ViewGroup) findViewById(R.id.MainParent));
答案 1 :(得分:1)
点击任何操作后执行以下步骤:
EditText firstEditText = (EditText) findViewById(R.id.yoursXmlId);
firstEditText.setText("");
答案 2 :(得分:1)
LinearLayout group = (LinearLayout)findViewById(R.id.MainParent);
for (int i = 0, count = group.getChildCount(); i < count; ++i)
{
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}