TextView text = (TextView) findViewById(R.id.tv);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// on click
}
});
@BindView(R.id.tv) TextView mTextView;
@OnClick({R.id.tv, R.id.btn})
public void onSomethingClick() {
// on click
}
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BindView {
int value();
}
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface OnClick {
int[] value();
}
public class ViewFinder {
private static final ActivityProvider PROVIDER_ACTIVITY = new ActivityProvider();
private static final ViewProvider PROVIDER_VIEW = new ViewProvider();
public static void inject(Activity activity) {
inject(activity, activity, PROVIDER_ACTIVITY);
}
public static void inject(View view) {
// for view
inject(view, view);
}
public static void inject(Object host, View view) {
// for fragment
inject(host, view, PROVIDER_VIEW);
}
public static void inject(Object host, Object source, Provider provider) {
// how to implement ?
}
}
public interface Finder<T> {
void inject(T host, Object source, Provider provider);
}
public class MainActivity$$Finder implements Finder<MainActivity> {
@Override
public void inject(final MainActivity host, Object source, Provider provider) {
host.mTextView = (TextView) (provider.findView(source, 2131427414));
host.mButton = (Button) (provider.findView(source, 2131427413));
host.mEditText = (EditText) (provider.findView(source, 2131427412));
View.OnClickListener listener;
listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
host.onButtonClick();
}
};
provider.findView(source, 2131427413).setOnClickListener(listener);
listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
host.onTextClick();
}
};
provider.findView(source, 2131427414).setOnClickListener(listener);
}
}
public class ViewFinder {
// same as above
private static final Map<String, Finder> FINDER_MAP = new HashMap<>();
public static void inject(Object host, Object source, Provider provider) {
String className = host.getClass().getName();
try {
Finder finder = FINDER_MAP.get(className);
if (finder == null) {
Class<?> finderClass = Class.forName(className + "$$Finder");
finder = (Finder) finderClass.newInstance();
FINDER_MAP.put(className, finder);
}
finder.inject(host, source, provider);
} catch (Exception e) {
throw new RuntimeException("Unable to inject for " + className, e);
}
}
}
compile project(':viewfinder-annotation')
compile 'com.squareup:javapoet:1.7.0'
compile 'com.google.auto.service:auto-service:1.0-rc2'
@AutoService(Processor.class)
public class ViewFinderProcesser extends AbstractProcessor {
/**
* 使用 Google 的 auto-service 库可以自动生成 META-INF/services/javax.annotation.processing.Processor 文件
*/
private Filer mFiler; //文件相关的辅助类
private Elements mElementUtils; //元素相关的辅助类
private Messager mMessager; //日志相关的辅助类
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
mFiler = processingEnv.getFiler();
mElementUtils = processingEnv.getElementUtils();
mMessager = processingEnv.getMessager();
}
/**
* @return 指定哪些注解应该被注解处理器注册
*/
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> types = new LinkedHashSet<>();
types.add(BindView.class.getCanonicalName());
types.add(OnClick.class.getCanonicalName());
return types;
}
/**
* @return 指定使用的 Java 版本。通常返回 SourceVersion.latestSupported()。
*/
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// to process annotations
return false;
}
}
package com.example;
public class Foo { // TypeElement
private int a; // VariableElement
private Foo other; // VariableElement
public Foo() {} // ExecuteableElement
public void setA( // ExecuteableElement
int newA // TypeElement
) {
}
}
public class BindViewField {
private VariableElement mFieldElement;
private int mResId;
public BindViewField(Element element) throws IllegalArgumentException {
if (element.getKind() != ElementKind.FIELD) {
throw new IllegalArgumentException(
String.format("Only fields can be annotated with @%s", BindView.class.getSimpleName()));
}
mFieldElement = (VariableElement) element;
BindView bindView = mFieldElement.getAnnotation(BindView.class);
mResId = bindView.value();
}
// some getter methods
}
public class AnnotatedClass {
public TypeElement mClassElement;
public List<BindViewField> mFields;
public List<OnClickMethod> mMethods;
public Elements mElementUtils;
// omit some easy methods
public JavaFile generateFinder() {
// method inject(final T host, Object source, Provider provider)
MethodSpec.Builder injectMethodBuilder = MethodSpec.methodBuilder("inject")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addParameter(TypeName.get(mClassElement.asType()), "host", Modifier.FINAL)
.addParameter(TypeName.OBJECT, "source")
.addParameter(TypeUtil.PROVIDER, "provider");
for (BindViewField field : mFields) {
// find views
injectMethodBuilder.addStatement("host.$N = ($T)(provider.findView(source, $L))", field.getFieldName(),
ClassName.get(field.getFieldType()), field.getResId());
}
if (mMethods.size() > 0) {
injectMethodBuilder.addStatement("$T listener", TypeUtil.ANDROID_ON_CLICK_LISTENER);
}
for (OnClickMethod method : mMethods) {
// declare OnClickListener anonymous class
TypeSpec listener = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(TypeUtil.ANDROID_ON_CLICK_LISTENER)
.addMethod(MethodSpec.methodBuilder("onClick")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(TypeName.VOID)
.addParameter(TypeUtil.ANDROID_VIEW, "view")
.addStatement("host.$N()", method.getMethodName())
.build())
.build();
injectMethodBuilder.addStatement("listener = $L ", listener);
for (int id : method.ids) {
// set listeners
injectMethodBuilder.addStatement("provider.findView(source, $L).setOnClickListener(listener)", id);
}
}
// generate whole class
TypeSpec finderClass = TypeSpec.classBuilder(mClassElement.getSimpleName() + "$$Finder")
.addModifiers(Modifier.PUBLIC)
.addSuperinterface(ParameterizedTypeName.get(TypeUtil.FINDER, TypeName.get(mClassElement.asType())))
.addMethod(injectMethodBuilder.build())
.build();
String packageName = mElementUtils.getPackageOf(mClassElement).getQualifiedName().toString();
// generate file
return JavaFile.builder(packageName, finderClass).build();
}
}
@AutoService(Processor.class)
public class ViewFinderProcesser extends AbstractProcessor {
private Map<String, AnnotatedClass> mAnnotatedClassMap = new HashMap<>();
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// process() will be called several times
mAnnotatedClassMap.clear();
try {
processBindView(roundEnv);
processOnClick(roundEnv);
} catch (IllegalArgumentException e) {
error(e.getMessage());
return true; // stop process
}
for (AnnotatedClass annotatedClass : mAnnotatedClassMap.values()) {
try {
info("Generating file for %s", annotatedClass.getFullClassName());
annotatedClass.generateFinder().writeTo(mFiler);
} catch (IOException e) {
error("Generate file failed, reason: %s", e.getMessage());
return true;
}
}
return true;
}
private void processBindView(RoundEnvironment roundEnv) throws IllegalArgumentException {
for (Element element : roundEnv.getElementsAnnotatedWith(BindView.class)) {
AnnotatedClass annotatedClass = getAnnotatedClass(element);
BindViewField field = new BindViewField(element);
annotatedClass.addField(field);
}
}
private void processOnClick(RoundEnvironment roundEnv) {
// same as processBindView()
}
private AnnotatedClass getAnnotatedClass(Element element) {
TypeElement classElement = (TypeElement) element.getEnclosingElement();
String fullClassName = classElement.getQualifiedName().toString();
AnnotatedClass annotatedClass = mAnnotatedClassMap.get(fullClassName);
if (annotatedClass == null) {
annotatedClass = new AnnotatedClass(classElement, mElementUtils);
mAnnotatedClassMap.put(fullClassName, annotatedClass);
}
return annotatedClass;
}
}
compile project(':viewfinder-annotation')
compile project(':viewfinder')
apt project(':viewfinder-compiler')
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv) TextView mTextView;
@BindView(R.id.btn) Button mButton;
@BindView(R.id.et) EditText mEditText;
@OnClick(R.id.btn)
public void onButtonClick() {
Toast.makeText(this, "onButtonClick", Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.tv)
public void onTextClick() {
Toast.makeText(this, "onTextClick", Toast.LENGTH_SHORT).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewFinder.inject(this);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有