利用反射获取ViewBinding

public abstract class CommonAdapter<Data, Binding extends ViewBinding> extends BaseAdapter {

    @SuppressWarnings("unchecked")
    private Binding onCreateViewBinding(LayoutInflater inflater, ViewGroup parent) {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class<?> clazz = (Class) Objects.requireNonNull(type).getActualTypeArguments()[1];
        try {
            Method method = clazz.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            return (Binding) method.invoke(null, inflater, parent, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

参考链接:

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

发表评论