2

I'm looking a way for get all views in layout file, I tried using getChildCount() but it not returns sub-child and sub-sub-child etc...

I want this because I have 64 Text View and I'll create loop for give them own font.

Taha Sami
  • 1,565
  • 1
  • 16
  • 43

1 Answers1

1

I assume you're using Java, for each View, you should check if it's a ViewGroup (can have children) or not, and if it does, we should recursively check for children as well so it can be written like this:

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);
            }
        }
    }
}

And you can use it in your fragment/activity/view like below:

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

Edit If you want to set font, this is not a good approach, try to use theme and style. This answer is a good example

Amin
  • 3,056
  • 4
  • 23
  • 34
  • Also if the order of children matters, you can turn it into a BFS or something view hierarchy is a tree – Amin Jun 21 '21 at 19:19