第一步:创建 InjectView 注解类(@annotation)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectView {
int value();
}
第二步:创建基类BaseActivity,在基类 里添加方法:
@Override
public void setContentView(int portLayoutResID) {
super.setContentView(portLayoutResID);
injectViews();
}
/**
* 注入组件
*/
private void injectViews() {
Class> clazz = ((Object) this).getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
InjectView injectView = field.getAnnotation(InjectView.class);
if (injectView != null) {
field.setAccessible(true);
try {
field.set(this, findViewById(injectView.value()));
} catch (IllegalAccessException e) {
LogUtil.e(((Object) this).getClass().getSimpleName(), "", e);
// log.error("", e);
} catch (Exception e) {
// log.error("field:" + field.getName(), e);
LogUtil.e(((Object) this).getClass().getSimpleName(), "", e);
throw new RuntimeException(e);
}
}
}
}
第三步 继承基类BaseActivity,调用注解:例如
public class TestAtivity extends BaseActivity{
@InjectView(R.id.go_back)
private LinearLayout btnBack;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxxx);
}
}