您的位置:首页 > 其它

自定义注解 获取控件id

2016-08-23 00:00 239 查看
第一步:创建 InjectView 注解类(@annotation)

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectView {
int value();
}

第二步:创建基类BaseActivity,在基类 里添加方法:

@Override
public void setContentView(int portLayoutResID) {
super.setContentView(portLayoutResID);
injectViews();
}

/**
* 注入组件
*/
private void injectViews() {
Class<?> clazz = ((Object) this).getClass();
Field[] fields = clazz.getDeclaredFields();

for (Field field : fields) {
InjectView injectView = field.getAnnotation(InjectView.class);
if (injectView != null) {
field.setAccessible(true);
try {
field.set(this, findViewById(injectView.value()));
} catch (IllegalAccessException e) {
LogUtil.e(((Object) this).getClass().getSimpleName(), "", e);
// log.error("", e);
} catch (Exception e) {
// log.error("field:" + field.getName(), e);
LogUtil.e(((Object) this).getClass().getSimpleName(), "", e);
throw new RuntimeException(e);
}
}
}
}

第三步 继承基类BaseActivity,调用注解:例如

public class TestAtivity extends BaseActivity{

@InjectView(R.id.go_back)
private LinearLayout btnBack;

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

setContentView(R.layout.xxxx);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: