美文网首页
Android 自定义注解

Android 自定义注解

作者: micki_zhou | 来源:发表于2017-11-24 17:45 被阅读69次

近来研究了一下android自定义注解,参考ButterKnife,实现一个注解布局

1. 创建一个注解类,activity默认方法是setContentView(),那自定义的注解类就叫BindContentView吧

/**
 * Created by micki on 2017/11/24.
 * activity布局id注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface BindContentView {
    int value();
}

2. 创建好注解类后,要解析处理这个注解类

/**
 * Created by micki on 2017/11/24.
 * 注解处理
 */

public class AnnotationUtils {

    public static void injectContentView(Activity activity) {
        Class a = activity.getClass();
        if (a.isAnnotationPresent(BindContentView.class)) { // 获取注解类
            BindContentView bindContentView = (BindContentView) a.getAnnotation(BindContentView.class); 
            int layoutId = bindContentView.value(); // 得到传入注解类布局id
            try {
                Method method = a.getMethod("setContentView", int.class);
                method.setAccessible(false);
                method.invoke(activity, layoutId);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
}

3. 然后就可以在activity里面使用咯

@BindContentView(R.layout.activity_main) // 传入布局id
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AnnotationUtils.injectContentView(this); // 注册注解类
    }

}

4. 顺带附上kotlin版本

/**
 * Created by micki on 2017/11/24.
 * activity布局id注解
 */
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE)
annotation class BindContentViewK(val value: Int)
/**
 * Created by micki on 2017/11/24.
 * 注解处理
 */
object AnnotationUtilsK {

     fun injectContentView(activity: Activity) {
        val a = activity.javaClass
        if (a.isAnnotationPresent(BindContentViewK::class.java)) {
            val contentView = a.getAnnotation(BindContentViewK::class.java) as BindContentViewK
            val layoutId = contentView.value
            try {
                val method = a.getMethod("setContentView", Int::class.javaPrimitiveType)
                method.isAccessible = false
                method.invoke(activity, layoutId)
            } catch (e: NoSuchMethodException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            } catch (e: InvocationTargetException) {
                e.printStackTrace()
            }

        }
    }
}

是不是超简单呢,按照这个方式,也可以自己定义findViewById,onClick等等,可以打造一个自己的ButterKnife了

相关文章

网友评论

      本文标题:Android 自定义注解

      本文链接:https://www.haomeiwen.com/subject/rrpfbxtx.html