package com.atmob.keyboard_android.util;

import android.view.View;
import android.view.ViewGroup;

/**
 * View树工具类
 */
public class ViewTreeHelper {
    /**
     * 递归遍历ViewGroup的子View，找到第一个符合目标类型的View
     *
     * @param root        待遍历的根布局
     * @param targetClass 目标View的Class类型
     * @return 找到的目标View，未找到则返回null
     */
    public static <T> T findTargetView(ViewGroup root, Class<T> targetClass) {
        if (root == null || targetClass == null) {
            throw new IllegalArgumentException("root and targetClass must not be null");
        }

        for (int i = 0; i < root.getChildCount(); i++) {
            View child = root.getChildAt(i);

            // 检查当前子View，是否是目标类型
            if (targetClass.isInstance(child)) {
                return targetClass.cast(child);
            }

            // 如果当前子View是ViewGroup，则递归遍历其子View
            if (child instanceof ViewGroup) {
                T result = findTargetView((ViewGroup) child, targetClass);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }
}