java获取控件id方法_自定义注解 获取控件id

本文介绍了如何在Java中通过创建自定义注解`InjectView`实现控件ID的获取和注入。首先定义注解类,然后在基类BaseActivity中解析注解并设置视图,最后在子类中使用注解绑定控件。
摘要由CSDN通过智能技术生成

第一步:创建 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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值