注解:
其实注解这东西说神秘也不神秘,因为在各种项目中我们一直有用。比如Spring3中能见到,在android的一些快速开发框架中也能看到。但是说它不神秘,其实也是蛮神秘的,虽然我一直都有接触这个功能,但却从来没仔细的去关注过它是怎么实现的。这次我就打算以android视图的注解缺了解它的原理,让他不再那么神秘了。
百度知道解开了我对注解的迷糊,下面是百度知道上的截图:
注解对象可以分为对 包,类,字段,构造方法,方法,参数等进行注解。
有了以上的理解后,我们就不多说了,直接上代码
<pre name="code" class="java" style="font-weight: bold;">public<pre name="code" class="java" style="font-weight: bold;">public abstract <span style="font-family: Arial, Helvetica, sans-serif;">class BaseBindActivity extends Activity {</span>
@Overrideprotected final void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);bindLayout();try {bindView();} catch (Exception e) {e.printStackTrace();throw new RuntimeException("绑定出错");}onCreated(savedInstanceState);}public void onCreated(Bundle savedInstanceState) {}@Retention(RetentionPolicy.RUNTIME)// 运行时获得@Target(ElementType.FIELD)// 针对字段的注解protected @interface BindView {int viewId();}@Retention(RetentionPolicy.RUNTIME)// 运行时获得@Target(ElementType.TYPE)// 针对类的注解protected @interface BindLayout{int layoutId();}private void bindView() throws IllegalArgumentException, IllegalAccessException {
<span style="white-space:pre"> </span>//获取所有成员变量
Field[] fs = getClass().getDeclaredFields();
if (fs != null) {
for (Field f : fs) {
BindView ma = f.getAnnotation(BindView.class);
System.err.println(f.getName());
if (ma != null) {<span style="font-family: Arial, Helvetica, sans-serif;">//如果能找到注解就开始绑定</span>
View v = findViewById(ma.viewId());
if (v != null) {
f.setAccessible(true);
f.set(this, f.getType().cast(v));
} else {
throw new RuntimeException("没有找到指定id的View绑定到:"
+ f.getName());
}
}
}
}
}
private void bindLayout(){
BindLayout bl = getClass().getAnnotation(BindLayout.class);
if(bl==null){
throw new RuntimeException("没有绑定layout文件");
}
int id = bl.layoutId();
if(id==0)
throw new RuntimeException("绑定的layout文件无效");
setContentView(id);
}
}
1.继承Activity,方便使用它的一些方法,比如setContentView,findViewById等
2.声明注解接口:BindView,BindLayout
3.重新oncreate方法,对该方法加final关键字,保证不被子类改写
4.实现bindLayout 方法,完成绑定layout文件
5.实现bindView方法,完成对View及其子类的成员变量的绑定
6.声明一个oncreated方法,让子类去复写,完成本应在Oncreate方法中完成的逻辑
现在父类准备了号看看在子类怎么去用
@BindLayout(layoutId = R.layout.activity_main)
public class MainActivity extends BaseBindActivity {
@BindView(viewId = R.id.tv)
private TextView tv;
@Override
public void onCreated(Bundle savedInstanceState) {
ComponentName cn = new ComponentName(this, "testauto.B");
PackageManager pm = getPackageManager();
int state = pm.getComponentEnabledSetting(cn);
tv.setText(state+" "+android.os.Build.MODEL);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
1.继承BaseBindActivity
2.在类声明的地方加上 @BindLayout(layoutId = R.layout.activity_main) , R.layout.activity_main 是你要绑定的layout文件
3.在声明成员视图变量时 加上@BindView(viewId = R.id.tv) R.id.tv是你想要绑定View的Id