利用反射获取ViewBinding

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Objects;

public class ViewBindingUtil {

    public static <Binding extends ViewBinding> Binding create(Class<?> bindingClazz, LayoutInflater inflater) {
        return create(bindingClazz, inflater, null);
    }

    public static <Binding extends ViewBinding> Binding create(Class<?> bindingClazz, LayoutInflater inflater, ViewGroup root) {
        return create(bindingClazz, inflater, root, false);
    }

    @SuppressWarnings("unchecked")
    @NonNull
    public static <Binding extends ViewBinding> Binding create(Class<?> bindingClazz, LayoutInflater inflater, ViewGroup root, boolean attachToRoot) {
        ParameterizedType parameterizedType = (ParameterizedType) bindingClazz.getGenericSuperclass();
        Type[] types = Objects.requireNonNull(parameterizedType).getActualTypeArguments();
        Class<?> clazz = null;
        Binding binding = null;
        for (Type type : types) {
            Class<?> temp = (Class<?>) type;
            if (ViewBinding.class.isAssignableFrom(temp)) {
                clazz = temp;
            }
        }
        if (clazz != null) {
            try {
                Method method = clazz.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
                binding = (Binding) method.invoke(null, inflater, root, attachToRoot);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Objects.requireNonNull(binding);
    }
}

参考链接:

利用ViewBinding和反射封装的基类,从此再也不用findViewById了

发表评论