kco*_*ock 122
我已经在一些我目前没有的代码中做了类似的事情,但是从内存中它应该是这样的(假设父视图LinearLayout的id为"layout"):
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;
}
Run Code Online (Sandbox Code Playgroud)
Kal*_*mah 19
要通过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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 Kotlin 进行编写,Android Jetpack 的Kotlin 扩展 (KTX)提供了用于迭代 ViewGroup 子项的扩展函数。
myViewGroup.forEach { ... }
myViewGroup.forEachIndexed { index, view -> ... }
Run Code Online (Sandbox Code Playgroud)
只需将依赖项添加到您的应用程序即可。检查上面的链接以获取最新版本。
implementation "androidx.core:core-ktx:1.2.0"
Run Code Online (Sandbox Code Playgroud)
这些扩展包含大量有用的功能,否则会被记录为样板。现在值得一试,以节省未来的时间!
| 归档时间: |
|
| 查看次数: |
39062 次 |
| 最近记录: |