我有一个带有无线电、输入和一个按钮的视图,当我单击它时,我想检查所有输入是否包含信息。如何在活动中迭代视图的元素并检查是否每个文本视图都满足上述要求?谢谢。
发布于 2011-01-27 05:43:47
我已经在一些我目前没有的代码中做了类似的事情,但在内存中应该是这样的(假设一个id为“LinearLayout”的父视图布局):
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
boolean success = formIsValid(layout);
public boolean formIsValid(LinearLayout layout) {
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v instanceof EditText) {
//validate your EditText here
} else if (v instanceof RadioButton) {
//validate RadioButton
} //etc. If it fails anywhere, just return false.
}
return true;
}
发布于 2016-06-18 17:14:18
要通过kcoppock递归应用该方法,可以将其更改为:
private void loopViews(ViewGroup view) {
for (int i = 0; i < view.getChildCount(); i++) {
View v = view.getChildAt(i);
if (v instanceof EditText) {
// Do something
} else if (v instanceof ViewGroup) {
this.loopViews((ViewGroup) v);
}
}
}
发布于 2020-03-29 11:20:59
如果你是用Kotlin编写的,Android Jetpack的Kotlin extensions (KTX)提供了遍历视图组子对象的扩展函数。
myViewGroup.forEach { ... }
myViewGroup.forEachIndexed { index, view -> ... }
只需将依赖项添加到您的应用程序中。请查看上面的链接以获取最新版本。
implementation "androidx.core:core-ktx:1.2.0"
这些扩展包含了大量有用的函数,否则就会被记为样板。现在就去看看吧,这样以后就可以节省时间了!
https://stackoverflow.com/questions/4809834
复制相似问题