Android 标识绑定View

如有不对的地方,望各路大神指点,小女子在此谢过,(*^__^*) 嘻嘻……,要是觉得不错,记得给个赞哦

 

1.Injector类

package com.mobivans.stock.tools.annotation;

import android.app.Activity;
import android.view.View;

import java.lang.reflect.Field;
import java.util.List;



public class Injector {

    /**
     * 注入绑定view
     *
     * @param fieldOwner
     * @param activity
     */
    public static void inject(Object fieldOwner, Activity activity) {
        try {
            // 绑定View
            injectView(fieldOwner, activity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 注入绑定view
     *
     * @param fieldOwner
     * @param view
     */
    public static void inject(Object fieldOwner, View view) {
        try {
            // 绑定View
            injectView(fieldOwner, view);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void injectView(Object fieldOwner, Object viewProvider) throws Exception {
        List<Field> fields = ReflectUtils.getFields(fieldOwner.getClass());
        for (Field field : fields) {
            ViewId viewId = field.getAnnotation(ViewId.class);
            if (viewId == null) {
                continue;
            }
            Object view = null;
            if (viewProvider instanceof Activity) {
                view = ((Activity) viewProvider).findViewById(viewId.value());
            } else if (viewProvider instanceof View) {
                view = ((View) viewProvider).findViewById(viewId.value());
            }
            if (view != null) {
                field.setAccessible(true);
                field.set(fieldOwner, view);
            }
        }
    }
}

2.ReflectUtils类

package com.mobivans.stock.tools.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @describe:反射相关辅助函数
 */

public class ReflectUtils {

    /**
     * 反射调用类成员函数
     *
     * @param instance
     * @param name
     * @param paramTypes
     * @param paramValues
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static Object invokeMethod(Object instance, String name, Class<?>[] paramTypes, Object[] paramValues)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<?> clazz = instance.getClass();
        Method method = getMethod(clazz, name, paramTypes);
        method.setAccessible(true);
        return method.invoke(instance, paramValues);
    }

    /**
     * 反射调用类静态成员函数
     *
     * @param clazz
     * @param name
     * @param paramTypes
     * @param paramValues
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static Object invokeStaticMethod(Class<?> clazz, String name, Class<?>[] paramTypes, Object[] paramValues)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = getMethod(clazz, name, paramTypes);
        method.setAccessible(true);
        return method.invoke(clazz, paramValues);
    }

    /**
     * 设置类成员变量
     *
     * @param instance
     * @param name
     * @param value
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static void setFieldValue(Object instance, String name, Object value) throws NoSuchFieldException, IllegalAccessException {
        Class<?> clazz = instance.getClass();
        Field field = getField(clazz, name);
        field.setAccessible(true);
        field.set(instance, value);
    }

    /**
     * 设置类静态成员变量
     *
     * @param clazz
     * @param name
     * @param value
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static void setStaticFieldValue(Class<?> clazz, String name, Object value) throws NoSuchFieldException, IllegalAccessException {
        Field field = getField(clazz, name);
        field.setAccessible(true);
        field.set(clazz, value);
    }

    /**
     * 获取类属性值
     *
     * @param instance
     * @param name
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static Object getFieldValue(Object instance, String name) throws NoSuchFieldException, IllegalAccessException {
        Class<?> clazz = instance.getClass();
        Field field = getField(clazz, name);
        field.setAccessible(true);
        return field.get(instance);
    }

    /**
     * 获取类静态属性值
     *
     * @param clazz
     * @param name
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static Object getStaticFieldValue(Class<?> clazz, String name) throws NoSuchFieldException, IllegalAccessException {
        Field field = getField(clazz, name);
        field.setAccessible(true);
        return field.get(clazz);
    }

    /**
     * 获取类所有成员变量
     *
     * @param instance
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getFieldMap(Object instance) throws IllegalAccessException {
        return getFieldMapInternal(instance.getClass(), instance, false);
    }

    /**
     * 获取类所有静态变量
     *
     * @param clazz
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getStaticFieldMap(Class<?> clazz) throws IllegalAccessException {
        return getFieldMapInternal(clazz, null, true);
    }

    /**
     * 获取类所有成员变量,包含定义在父类的成员
     *
     * @param clazz
     * @return
     */
    public static List<Field> getFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<Field>();
        for (Field field : clazz.getDeclaredFields()) {
            fields.add(field);
        }
        if ((clazz != Object.class) && (clazz.getSuperclass() != null)) {
            fields.addAll(getFields(clazz.getSuperclass()));
        }
        return fields;
    }

    /**
     * 获取类所有成员函数,包含定义在父类的成员
     *
     * @param clazz
     * @return
     */
    public static List<Method> getMethods(Class<?> clazz) {
        List<Method> methods = new ArrayList<Method>();
        for (Method method : clazz.getDeclaredMethods()) {
            methods.add(method);
        }
        if ((clazz != Object.class) && (clazz.getSuperclass() != null)) {
            methods.addAll(getMethods(clazz.getSuperclass()));
        }
        return methods;
    }

    /**
     * 判断一个类是否集成自另一个类
     *
     * @param child
     * @param parent
     * @return
     */
    public static boolean isSubClassOf(Class<?> child, Class<?> parent) {
        if (child == null) {
            return false;
        }
        if (child == parent) {
            return true;
        }
        if (child == Object.class) {
            return false;
        }
        return isSubClassOf(child.getSuperclass(), parent);
    }

    private static Method getMethod(Class<?> clazz, String name, Class<?>[] paramTypes) throws NoSuchMethodException {
        try {
            return clazz.getDeclaredMethod(name, paramTypes);
        } catch (NoSuchMethodException e) {
            if (clazz.getSuperclass() != null) {
                return getMethod(clazz.getSuperclass(), name, paramTypes);
            } else {
                throw e;
            }
        }
    }

    private static Field getField(Class<?> clazz, String name) throws NoSuchFieldException {
        try {
            return clazz.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
            if (clazz.getSuperclass() != null) {
                return getField(clazz.getSuperclass(), name);
            } else {
                throw e;
            }
        }
    }

    private static Map<String, Object> getFieldMapInternal(Class<?> clazz, Object instance, boolean isStatic) throws IllegalAccessException {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Field> fields = getFields(clazz);
        for (Field field : fields) {
            field.setAccessible(true);
            if (isStatic && Modifier.isStatic(field.getModifiers())) {
                result.put(field.getName(), field.get(clazz));
            } else {
                if (instance == null) {
                    continue;
                }
                result.put(field.getName(), field.get(instance));
            }
        }
        return result;
    }
}

3.ViewId

package com.mobivans.stock.tools.annotation;

import android.view.View;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @describe:标识绑定的View
 */

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ViewId {

    int value() default View.NO_ID;
}

 

使用方法:

@ViewId(R.id.home_recycleView)
    MyRecyclerView recyclerView;

在Activity的oncreate方法初始化

  @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        Injector.inject(this, this);
 
    }

在fragment的onCreateView()方法初始化

  @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_information, container, false);
        Injector.inject(this, view);
    
        return view;
    }

 

注意:别忘记了初始化哦

 

 

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值