本文是使用注解代替findViewById的简单使用,在此之前,必须要了解什么是元注解,元注解有哪些,作用是什么?
注解的概念是java5.0提出来的,元注解主要有四种:
- @Target:说明了注解修饰的范围
- @Retention:定义了注解被保留的时间
- @Documented:表示可以被诸如javadoc此类工具文档化
- @Inherited:阐述了某个被标注的类型是被继承的
具体可参考:【注解】自定义注解及元注解
- 首先定义一个BindView注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by yds
* on 2020/3/4.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BindView {
int value();
}
- 定义一个注解实现类DragonFly
import android.app.Activity;
import androidx.annotation.NonNull;
import androidx.annotation.UiThread;
import java.lang.reflect.Field;
/**
* Created by yds
* on 2020/3/4.
*/
public class DragonFly {
@NonNull
@UiThread
public static void bind(@NonNull Activity target) {
Class<?> clazz = target.getClass();
Field[] fields = clazz.getDeclaredFields();
if (fields == null || fields.length == 0) {
return;
}
for (Field field : fields) {
if (field.isAnnotationPresent(BindView.class)) {
BindView bindView = field.getAnnotation(BindView.class);
int value = bindView.value();
if (value > 0) {
field.setAccessible(true);
try {
field.set(target, target.findViewById(value));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
- 使用
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.annotationdemo.annotationdefine.BindView;
import com.example.annotationdemo.annotationdefine.DragonFly;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv)
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DragonFly.bind(this);
mTextView.setText("测试");
}
}
网友评论