本文是使用註解代替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("測試");
}
}