BufferKnife原理-注解

前言:

ButterKnife是一个专注于Android系统的View注入框架,以前总是要写很多findViewById来找到View对象,有了ButterKnife可以很轻松的省去这些步骤。是大神JakeWharton的力作,目前使用很广。最重要的一点,使用ButterKnife对性能基本没有损失,因为ButterKnife用到的注解并不是在运行时反射的,而是在编译的时候生成新的class。项目集成起来也是特别方便,使用起来也是特别简单。

 

原理:

 
/**
 * Bind a field to the view for the specified ID. The view will automatically be cast to the field
 * type.
 * 

 * {@literal @}BindView(R.id.title) TextView title;
 * 
*/ @Retention(RUNTIME) @Target(FIELD) public @interface BindView { /** View ID to which the field will be bound. */ @IdRes int value(); }

 

@Retention(RUNTIME) 和 @Target(FIELD)这两个都是元注解,元注解是一种可以应用到其它注解上的基本注解。

@Retention:注解的保留期

- RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时它将被丢弃忽视。(参考@override

- RetentionPolicy.CLASS 注解只被保留到编译进行的时候,它并不会被加载到 JVM 中。

- RetentionPolicy.RUNTIME 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们。

 

@Target:作用域

ElementType.ANNOTATION_TYPE 可以给一个注解进行注解

ElementType.CONSTRUCTOR 可以给构造方法进行注解

ElementType.FIELD 可以给属性进行注解

ElementType.LOCAL_VARIABLE 可以给局部变量进行注解

ElementType.METHOD 可以给方法进行注解

ElementType.PACKAGE 可以给一个包进行注解

ElementType.PARAMETER 可以给一个方法内的参数进行注解

ElementType.TYPE 可以给一个类型进行注解,比如类、接口、枚举

 

仿照这个方式写个注解:

 

@Retention(RUNTIME)//运行时注解
@Target(TYPE)//作用域  类 接口

public @interface  ViewInject {

    int mainLayoutid() default  -1;//默认值-1
    
}

 使用方法:

 首先在基类

public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewInject annotation = this.getClass().getAnnotation(ViewInject.class);
        if (annotation  != null){
            int mainLayoutid = annotation.mainLayoutid();
            if (mainLayoutid >0){

                setContentView(mainLayoutid);
            }else{

                throw new RuntimeException("mainLayoutid <0");
            }
        }else{

            throw new RuntimeException("annotation = null");
        }

    }
}

  MainActivity继承基类,如图:

@ViewInject(mainLayoutid = R.layout.activity_main)
public class MainActivity extends BaseActivity {

    @BindView(R.id.vv_videoview)
    MVideoView m_videoView;

    @BindView(R.id.tv_skip)
    TextView m_skip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        initVideoView();
    }

    运行一下,画面正常,OVER


 

你可能感兴趣的:(Android开发,Andoid学习笔记)