有没有办法在运行时获取布局文件中的所有视图

Is there any way to get all views in layout file at runtime

我正在寻找一种获取布局文件中所有视图的方法,我尝试使用 getChildCount() 但它不是 returns 子子和子子子等...

我想要这个,因为我有 64 个文本视图,我将创建循环来为它们提供自己的字体。

我假设您正在使用 Java,对于每个视图,您应该检查它是否是 ViewGroup(可以有 children),如果是,我们也应该递归检查 children 所以它可以这样写:

class ViewExt{
    public static List<View> getAllSubviews(View parent){
        ArrayList<View> ans = new ArrayList<>();
        if( parent instanceof ViewGroup){
            fillChildren((ViewGroup) parent, ans);
        }
        return ans;
    }

    private static void fillChildren(ViewGroup parent, ArrayList<View> arr){
        for(int i=0 ; i < parent.getChildCount() ; i++){
            View child = parent.getChildAt(i):
            arr.add( child );
            if( child instanceof ViewGroup ){ // if it's a ViewGroup, extract it's children as well
                fillChildren( (ViewGroup) child , arr);
            }
        }
    }
}

您可以在 fragment/activity/view 中使用它,如下所示:

List<View> allSubviews = ViewExt.getAllSubviews( view );

编辑 如果你想设置字体,这不是一个好方法,尝试使用主题和样式。 This answer 就是一个很好的例子