用于初始化View的
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BindView {
int value() default 0;
}
用于点击事件的
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BindClick {
int value() default 0;
}
建一个类来处理数据
public class InjectUtils {
public static void inject(final Activity activity){
Class<? extends Activity> c = activity.getClass();
//属性
Field[] fields = c.getDeclaredFields();
for (Field f:fields) {
if (f.isAnnotationPresent(BindView.class)) {
int viewId = f.getAnnotation(BindView.class).value();
View view = activity.findViewById(viewId);
try {
f.setAccessible(true);
f.set(activity,view);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
//方法
Method[] methods = c.getDeclaredMethods();
for (final Method m:methods) {
BindClick click = m.getAnnotation(BindClick.class);
if (click!=null) {
int viewId = click.value();
activity.findViewById(viewId).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
m.setAccessible(true);
try {
m.invoke(activity);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
});
}
}
}
}
Activity中
public class MainActivity extends AppCompatActivity {
@BindView(R.id.btn)
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InjectUtils.inject(this);
}
@BindClick(R.id.btn)
private void play(){
Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();
}
}