自定义注解

public class MainActivity extends AppCompatActivity {

    @Injectview(ID =R.id.btn)
    private Button button;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewUtils.bind(this);

    }
    @OnClick(value = R.id.btn)
    private void OnClick(){
        Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
    }
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Injectview {

    int ID();


}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnClick {
    int value();
}

 

public class ViewUtils {
    public static void bind(Activity activity){
        bindFeild(activity);
        bindOnclick(activity);
    }

    private static void bindOnclick(final Activity activity) {
        Class clazz = activity.getClass();
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (final Method declaredMethod : declaredMethods) {
            OnClick annotation = declaredMethod.getAnnotation(OnClick.class);
            if (annotation!= null){
                int value = annotation.value();
                View view = activity.findViewById(value);
                declaredMethod.setAccessible(true);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            declaredMethod.invoke(activity);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                });



            }
        }


    }

    private static void bindFeild(Activity activity) {

        Class clazz = activity.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            Injectview annotation = declaredField.getAnnotation(Injectview.class);
            if (annotation != null){

                int id = annotation.ID();
                View viewById = activity.findViewById(id);
                declaredField.setAccessible(true);
                try {
                    declaredField.set(activity,viewById);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }


        }


    }
}

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(自定义注解)