Custom annotation
Because here to use reflection knowledge, so not familiar with the reflection of the need to review next Oh.
Create a new package injection, and define the annotation class Id under the package
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {
/**
* Control id to be bound
*
* @return
*/
int value();
}
Then create a new annotation resolution class FindView (the annotation is detailed, so you can understand it):
/**
* Annotation get Id resolution class
* Created by Chao on 2017-12-23.
*/
public class FindView {
public static void bind(Object context) {
Activity at = null;
//Judge the incoming context instance
if (context instanceof Activity) {
at = (Activity) context;
} else if (context instanceof Fragment) {
Fragment fr = (Fragment) context;
at = fr.getActivity();
}
// Get all member variables in this activity
Field[] fields = at.getClass().getDeclaredFields();
for (Field field : fields) {
// Get whether this annotation is printed on the variable
Id mId = field.getAnnotation(Id.class);
if (mId != null) {// There is this annotation.
int id = mId.value();// Get annotation value
if (id != 0) {
field.setAccessible(true);
Object view = null;
try {
view = at.findViewById(id);// Find control in Activity layout according to annotation ID
// Set field properties
field.set(at, view);// Set the field variable to the value view in at
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
Then bind in BaseActivity
private void init() {
FindView.bind(this);
initView();
initData();
initListener();
}
Test:
The test is successful. In the future, we only need to add @ Id to our Activity control to find the Id. of course, control monitoring is also a reason. You can expand it by yourself.
Source address: https://github.com/zhangzhichaolove/BasicsFrame