<pre name= "code" class= "HTML" > Layout code <linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" match_parent " android:o rientation= "vertical" > <textview android:layout_width= "fill_parent" android:textsize= "20SP" android:layout_height= "wrap_content" android:id= "@+id/tv"/> <button android:layout_ Width= "Fill_parent" android:layout_height= "wrap_content" android:id= "@+id/but"/> </ Linearlayout>
Father Activitypackage Com.young.android;import Java.lang.reflect.field;import Com.young.android.annotation.ViewInject; Import Com.young.android.exception.illegalparameterexception;import Android.app.activity;import Android.view.View ;p ublic class Youngactivity extends Activity {@Overridepublic void setcontentview (int layoutresid) {//TODO auto-generate D method Stubsuper.setcontentview (LAYOUTRESID); class<? Extends youngactivity> CLZ = GetClass (); field[] fs = Clz.getdeclaredfields (); for (Field f:fs) {Viewinject viewinject = f.getannotation (Viewinject.class); if (vie Winject! = NULL) {int id = viewinject.id (); View v = Findviewbyid (id), if (v = = null) throw new Illegalparameterexception ("@ViewInject argument is not valid, you should use this example: first define the T in the corresponding layout file EXTVIEW,ID is TV, then Mark @ViewInject (Id=r.id.tv) "Before the TextView of the Declaration), f.setaccessible (true); try {f.set (youngactivity.this, v) ;} catch (Illegalaccessexception e) {//TODO auto-generated catch Block//e.printstacktrace (); throw new Illegalparameterexception ("@ViewInject argument is not legal, you shouldThis example: first define TEXTVIEW,ID as TV in the corresponding layout file, and then label the @ViewInject (id=r.id.tv) before the textview of the Declaration);} catch (IllegalArgumentException e) {//TODO auto-generated catch Block//e.printstacktrace (); throw new Illegalparameterexception ("@ViewInject argument is not valid, you should use this example: first define TEXTVIEW,ID as TV in the corresponding layout file, and then label the @ViewInject before the TextView of the Declaration ( id=r.id.tv) ");} F.setaccessible (FALSE);}}}
Annotation definition Package Com.young.android.annotation;import java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target;@ Target (Elementtype.field) @Retention (retentionpolicy.runtime) public @interface viewinject {public int id () default 0;}
Exception package Com.young.android.exception;public class Illegalparameterexception extends runtimeexception{private static Final long serialversionuid = 839888641617782091L; Public illegalparameterexception (String detailmessage) {super (detailmessage);//TODO auto-generated constructor stub} }
Lightweight Android Framework source