注意:定义的控件变量必须是public,否则报错
1、添加类
package com.example.zhujie;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface BindView {
int value();
}
2、添加类
package com.example.zhujie;
import android.app.Activity;
import android.view.View;
import java.lang.reflect.Field;
//创建注解处理器
public class InjectUtils {
public static void inject(Activity activity) throws IllegalAccessException {
Field[] fields = activity.getClass().getDeclaredFields();
for (Field field : fields) {
BindView bindView = field.getAnnotation(BindView.class);
if (bindView != null) {
int value = bindView.value();
View view = activity.findViewById(value);
try {
field.set(activity, view);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
3、在activity中调用
package com.example.zhujie;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv)
public TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
InjectUtils.inject(this);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
textView.setText("测hi注解");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)