butterknife

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public@interfaceOnClick{

public intvalue();

}



@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

public@interfaceViewInject{

public intvalue();

}



public classViewUtils {

public static voidinject(Activity activity){

bindView(activity);

bindOnClick(activity);

}

private static voidbindOnClick(Activity activity) {

Class clazz = activity.getClass();

Field[] declaredFields = clazz.getDeclaredFields();

for(Field field : declaredFields) {

ViewInjectviewInject = field.getAnnotation(ViewInject.class);

if(viewInject !=null){

intresId = viewInject.value();

View view = activity.findViewById(resId);

field.setAccessible(true);

try{

field.set(activity,view);

}catch(IllegalAccessException e) {

e.printStackTrace();

}

}

}

}

private static voidbindView(finalActivity activity) {

Class clazz = activity.getClass();

Method[] declaredMethods = clazz.getDeclaredMethods();

for(finalMethod method : declaredMethods) {

OnClickonclick = method.getAnnotation(OnClick.class);

if(onclick !=null){

intresId = onclick.value();

finalView btn = activity.findViewById(resId);

btn.setOnClickListener(newView.OnClickListener() {

@Override

public voidonClick(View v) {

method.setAccessible(true);

try{

method.invoke(activity,btn);

}catch(Exception e) {

e.printStackTrace();

}

}

});

}

}

}

}



public classMainActivityextendsAppCompatActivity {

@ViewInject(R.id.tv1)

privateTextViewtv1;

@ViewInject(R.id.tv2)

privateTextViewtv2;

@Override

protected voidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ViewUtils.inject(this);

}

@OnClick(R.id.btn1)

public voidclick(View view){

Toast.makeText(this,"我被点击了",Toast.LENGTH_SHORT).show();

}

}

你可能感兴趣的:(butterknife)