从 parent 视图获取特定类型的视图

Get specific type of view from parent view

你们知道是否有正确的方法从 parent 视图中获取所有特定视图类型,如标题所述?

我想从我的 activity 获取所有 EditText 视图,所以我想知道是否有比使用此解决方案更好的方法 get all views from an activity 然后测试每个视图以检查它是否是 EditText还是不是?

感谢您的帮助,

弗洛里安

方法一:

假设您将编辑文本命名为 edittext_0、edittext_1、.. edittext_n。你可以这样做:

ViewGroup vg = (ViewGroup) view;
for (int i = 0; i < n; i++) {
    int id = vg.getResources().getIdentifier("edittext_"+i, "id", getPackageName());
     edittext[i] = (EditText) vg.findViewById(id);
}

实际上,如果您有大量视图,link 中指定的答案是可行的,但如果您想要来自 view/viewgroup 的特定类型的视图,只需使用 findViewById 方法. 示例:

(in Kotlin) //Similar syntax in java
val view : View = findViewById(your_layout_or_any_other_view)
val childView : EditText = view.findViewById(edittext_id)

选读

link中给出的答案的优化答案:

Kotlin 使用 for-in 循环更容易:

for (childView in ll.children) {
     if(childView.id == your_edittext_id) //If required
     //childView is a child of ll         
}
//Here ll is id of LinearLayout defined in layout XML.