原理是在Activity加載好後經過找到Activity中使用註解的字段,再經過Java反射的方式,動態的給這個字段設置值。android
1定義一個註解接口框架
/** * view inect by id * * @author Lucky * */ @Target(ElementType.FIELD)//表示用在字段上 @Retention(RetentionPolicy.RUNTIME)//表示在生命週期是運行時 public @interface ViewInject { int value() default 0; }
/** * * @author Lucky * */ public abstract class BaseActivity extends FragmentActivity { /** * get content view layout id * * @return */ public abstract int getLayoutId(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); autoInjectAllField(); } /** * 解析註解 */ public void autoInjectAllField() { try { Class<?> clazz = this.getClass(); Field[] fields = clazz.getDeclaredFields();//得到Activity中聲明的字段 for (Field field : fields) { // 查看這個字段是否有咱們自定義的註解類標誌的 if (field.isAnnotationPresent(ViewInject.class)) { ViewInject inject = field.getAnnotation(ViewInject.class); int id = inject.value(); if (id > 0) { field.setAccessible(true); field.set(this, this.findViewById(id));//給咱們要找的字段設置值 } } } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } }
3:這樣來使用ide
public class TestActivity extends BaseActivity { @ViewInject(R.id.claim_statement) private WebView mWebView; @Override public int getLayoutId() { // TODO Auto-generated method stub return R.layout.activity_claim; } }
相對於androidannotations,BufferKnife更簡單的粗暴,要是不單單限於findbyID 就根據需求去選擇這兩種比較經常使用的註解框架this