Android IOC依赖注入layout view 点击事件

github地址:https://github.com/feb07/IOCPro

1、概述

什么叫IOC,控制反转(Inversion of Control,英文缩写为IOC)。IOC框架也叫控制反转框架,依赖注入框架。IOC的核心是解耦,解耦的目的是修改耦合对象时不影响另外的对象,降低关联性,从Spring来看,在Spring中IOC更多的依赖的是xml配置,而Android的IOC不使用xml配置,使用注解+反射。一个类里面有很多个成员变量,传统的写法,要用这些成员变量,就new 出来用。IOC的原则是:不要new,这样耦合度太高;配置个xml文件,里面标明哪个类,里面用了哪些成员变量,等待加载这个类的时候,注入(new)进去;

2、实现

这里的Android IOC框架,主要是帮大家注入所有的控件,布局文件,点击事件。

举个例子,一个activity有十几个view,传统做法是设置布局文件,然后一个个findViewById。现在的做法,Activity类上添加个注解,帮我们自动注入布局文件;声明View的时候,添加一行注解,然后自动帮我们findViewById。

3、编码

1)注入布局文件

定义注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectContentView {
    int value();
}

InjectContentView用于在类上使用,主要用于标明该Activity需要使用的布局文件。

@InjectContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
}

简单说下注解,关键字@interface @Target @Retention。
@Target表示该注解可以用于什么地方,可能的类型TYPE(类),FIELD(成员变量),可能的类型:

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

@Retention表示:表示需要在什么级别保存该注解信息;我们这里设置为运行时。

可能的类型:

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

注入布局文件代码,通过获取注解的值,反射setContentView方法

public static void injectLayout(Activity activity) {
        Class<? extends Activity> clazz = activity.getClass();
        //获取InjectContentView注解
        InjectContentView contentview = clazz.getAnnotation(InjectContentView.class);
        if (contentview != null) {
            int layout = contentview.value();
            try {
                //获取setContentView方法
                Method method = clazz.getMethod("setContentView", int.class);
                method.setAccessible(true);
                method.invoke(activity, layout);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
2)注入view

定义注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectView {
    int value();
}
@InjectContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    @InjectView(R.id.btn)
    private Button btn;

    @InjectView(R.id.tv)
    private TextView tv;
}

注入view,获取所有的类的属性变量,通过获取注解的值,反射findViewById方法,设置给属性

public static void injectViews(Activity activity) {
        Class<? extends Activity> clazz = activity.getClass();
        //获取所有属性
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            InjectView injectview = field.getAnnotation(InjectView.class);
            if (injectview != null) {
                try {
                    int viewId = injectview.value();
                    Method method = clazz.getMethod("findViewById", int.class);
                    Object view = method.invoke(activity, viewId);
                    field.setAccessible(true);
                    field.set(activity, view);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
3)点击事件注入

正常写法:有三个要素,listener绑定方法setOnClickListener,事件类型View.OnClickListener,事件回调方法onClick

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "today is 2019-2-13", Toast.LENGTH_LONG).show();
            }
        });

定义注解

@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventBase {
    String listenerSetter();//setOnClickListener方法

    Class<?> listenerType();//View.OnClickListener

    String methodName();//onclick回调方法
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@EventBase(listenerSetter = "setOnClickListener", listenerType = View.OnClickListener.class, methodName = "onClick")
public @interface InjectClick {
    int[] value();
}

如果是onclick事件,可以按以上的写法,如果是onitemclick,只需要修改@EventBase三要素的value的值。同理可IOC注入Recyclerview、listview的onitemclick事件。
注入代码:涉及到动态方法代理,即用自定义方法clickMethod(View v),代理了原本的onclick(View v)方法, 需要注意的是代理方法的入参需要与被代理方法的入参一致。

@InjectClick(R.id.btn)
    public void clickMethod(View view) {
        Toast.makeText(MainActivity.this, "today is 2019-2-13", Toast.LENGTH_LONG).show();
    }
 public static void injectEvents(Activity activity) {
        Class<? extends Activity> clazz = activity.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            //拿到方法的所有注解
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                Class<? extends Annotation> annotationType = annotation.annotationType();
                //拿到注解的注解
                EventBase eventBaseAnnotation = annotationType.getAnnotation(EventBase.class);
                if (eventBaseAnnotation != null) {
                    String listenerSetter = eventBaseAnnotation.listenerSetter();
                    Class<?> listenerType = eventBaseAnnotation.listenerType();
                    String methodName = eventBaseAnnotation.methodName();

                    try {
                        ClickInvocationHandler handler = new ClickInvocationHandler(activity);
                        handler.addMethod(methodName, method);
                        Object listener = Proxy.newProxyInstance(listenerType.getClassLoader(), new Class<?>[]{listenerType}, handler);
                        Method value = annotationType.getDeclaredMethod("value");
                        int[] viewIds = (int[]) value.invoke(annotation, null);
                        for (int viewid : viewIds) {
                            View view = activity.findViewById(viewid);
                            Method setEventListenerMethod = view.getClass().getMethod(listenerSetter, listenerType);
                            setEventListenerMethod.invoke(view, listener);
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

java动态代理相关:Proxy与InvocationHandler

public class ClickInvocationHandler implements InvocationHandler {
    private Object target;
    private HashMap<String, Method> methodHashMap = new HashMap<>();

    public ClickInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        if (target != null) {
            method = methodHashMap.get(methodName);
            if (method != null) {
                return method.invoke(target, args);
            }
        }
        return null;
    }

    public void addMethod(String methodName, Method method) {
        methodHashMap.put(methodName, method);
    }
}

附上完整的InjectManager代码,以及BaseActivity代码

public class InjectManager {
    public static void inject(Activity activity) {
        injectLayout(activity);
        injectViews(activity);
        injectEvents(activity);
    }

    public static void injectLayout(Activity activity) {
        Class<? extends Activity> clazz = activity.getClass();
        //获取InjectContentView注解
        InjectContentView contentview = clazz.getAnnotation(InjectContentView.class);
        if (contentview != null) {
            int layout = contentview.value();
            try {
                //获取setContentView方法
                Method method = clazz.getMethod("setContentView", int.class);
                method.setAccessible(true);
                method.invoke(activity, layout);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static void injectViews(Activity activity) {
        Class<? extends Activity> clazz = activity.getClass();
        //获取所有属性
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            InjectView injectview = field.getAnnotation(InjectView.class);
            if (injectview != null) {
                try {
                    int viewId = injectview.value();
                    Method method = clazz.getMethod("findViewById", int.class);
                    Object view = method.invoke(activity, viewId);
                    field.setAccessible(true);
                    field.set(activity, view);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void injectEvents(Activity activity) {
        Class<? extends Activity> clazz = activity.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            //拿到方法的所有注解
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                Class<? extends Annotation> annotationType = annotation.annotationType();
                //拿到注解的注解
                EventBase eventBaseAnnotation = annotationType.getAnnotation(EventBase.class);
                if (eventBaseAnnotation != null) {
                    String listenerSetter = eventBaseAnnotation.listenerSetter();
                    Class<?> listenerType = eventBaseAnnotation.listenerType();
                    String methodName = eventBaseAnnotation.methodName();

                    try {
                        ClickInvocationHandler handler = new ClickInvocationHandler(activity);
                        handler.addMethod(methodName, method);
                        Object listener = Proxy.newProxyInstance(listenerType.getClassLoader(), new Class<?>[]{listenerType}, handler);
                        Method value = annotationType.getDeclaredMethod("value");
                        int[] viewIds = (int[]) value.invoke(annotation, null);
                        for (int viewid : viewIds) {
                            View view = activity.findViewById(viewid);
                            Method setEventListenerMethod = view.getClass().getMethod(listenerSetter, listenerType);
                            setEventListenerMethod.invoke(view, listener);
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
public class BaseActivity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        InjectManager.inject(this);
    }
}

MainActivity代码:可以看出在activity中,布局文件,view,点击事件的注入,使代码更简洁

@InjectContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    @InjectView(R.id.btn)
    private Button btn;

    @InjectView(R.id.tv)
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @InjectClick(R.id.btn)
    public void clickMethod(View view) {
        Toast.makeText(MainActivity.this, "today is 2019-2-13", Toast.LENGTH_LONG).show();
    }
}

4、github地址

https://github.com/feb07/IOCPro

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,635评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,628评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,971评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,986评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,006评论 6 394
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,784评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,475评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,364评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,860评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,008评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,152评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,829评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,490评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,035评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,428评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,127评论 2 356

推荐阅读更多精彩内容