xUtils系列之ViewUtils-ViewInject注解

ViewInject注解定义:

@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ViewInject { int value(); /* parent view id */ int parentId() default 0; }


ViewUtils中的注解部分:
ViewInject viewInject = field.getAnnotation(ViewInject.class); if (viewInject != null) { try { View view = finder.findViewById(viewInject.value(), viewInject.parentId()); if (view != null) { field.setAccessible(true); field.set(handler, view); } } catch (Throwable e) { LogUtils.e(e.getMessage(), e); } }


使用方法:


首先,创建如下两个布局文件:
activity_main.xml:


layout_include.xml:


MainActivity.java:
@ContentView(R.layout.activity_main) public class MainActivity extends Activity { @ViewInject(R.id.tv) public TextView tv; @ViewInject(value=https://www.it610.com/article/R.id.tv1_include,parentId=R.layout.layout_include) public TextView tv1_include; @ViewInject(R.id.tv2_include) public TextView tv2_include; //tv2_include虽然是在include布局中,但是它也在activity_main布局的视图树中, //所以不指定父id也能被找到, 实际上,注解中的parentId这个属性是多余的. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewUtils.inject(this); } }

    推荐阅读