android自定义注解初始化布局控件(二)

时间:2021-10-25 00:37:46

android中通过自定义注解代替setContentView和findViewById()的方法,如下:

定义布局的注解:

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface LayoutAnnotation {
public int layoutId() default R.layout.activity_main;
}
定义控件的注解:

@Documented
@Inherited
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewAnnotation {

public int viewId();
public String onclick() default "";
}

注解的处理类,通过反射的知识动态执行方法:

public class ViewUtils {

public static void injectView(Object object,Activity activity) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

Class clazz = object.getClass();
if(clazz.isAnnotationPresent(LayoutAnnotation.class)) {

LayoutAnnotation layoutAnnotation = (LayoutAnnotation) clazz.getAnnotation(LayoutAnnotation.class);//得到注解类
int layoutId = layoutAnnotation.layoutId();
Method method = clazz.getMethod("setContentView",int.class);//得到setContentView方法<pre name="code" class="java"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"><span style="white-space:pre"></span>method.setAccessible(true);</span>
method.invoke(object, layoutId);}Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {if (field.isAnnotationPresent(ViewAnnotation.class)) {ViewAnnotation viewAnnotation = field.getAnnotation(ViewAnnotation.class);int viewId = viewAnnotation.viewId();View view = activity.findViewById(viewId);field.setAccessible(true);field.set(object, view);}}}}

 

MainActivity.java如下:

@LayoutAnnotation(layoutId=R.layout.activity_main)
public class MainActivity extends Activity {
@ViewAnnotation(viewId=R.id.textone)
TextView textViewone;


@ViewAnnotation(viewId=R.id.btnone,onclick="onclick")
Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

try {
ViewUtils.injectView(this,this);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

textViewone.setText("测试一");
}


public void onclick(View view) {
Toast.makeText(MainActivity.this,"text",1000).show();
}


}