Android高效率编码-findViewById()的蜕变-注解,泛型,反射
16lz
2021-12-04
Android高效率编码-findViewById()的蜕变-注解,泛型,反射
Android的老朋友findViewById()篇!
先看看他每天是在干什么
//好吧,很多重复的,只不过想表达项目里确实有很多控件 mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.laft_drawer); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.laft_drawer); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.laft_drawer); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.laft_drawer); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.laft_drawer); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
1.泛型
//自己定义一个方法public T $(int viewID) { return (T) findViewById(viewID);}
然后使用的时候是这个样子的,其实就是简化了一个findViewById()罢了
mDrawerLayout = $(R.id.drawer_layout); mDrawerList = $(R.id.laft_drawer); mDrawerLayout = $(R.id.drawer_layout); mDrawerList = $(R.id.laft_drawer); mDrawerLayout = $(R.id.drawer_layout); mDrawerList = $(R.id.laft_drawer);
2.注解
注解的方法现在很流行,而且很多开源框架已经支持注解了,我就以Android Annotations框架为例,当然他不光只是能注解控件,还能做更多的事情,比如事件绑定,异步线程与UI线程的交互等…
这里提供一个架包的下载地址:http://download.csdn.net/detail/qq_26787115/9362755
初始化控件
//初始化控件 @ViewById(R.id.button1) private Button button1; @ViewById(R.id.button1) private Button button2; @ViewById(R.id.editText1) private EditText editText1;
3.反射
- http://www.mzule.com/%E4%BD%BF%E7%94%A8injectview%E5%92%8Cfindviewbyid%E8%AF%B4%E6%8B%9C%E6%8B%9C/
其实Android studio 上插件是可以一键生成findViewById的,详情可以看我的博文:http://blog.csdn.net/qq_26787115/article/details/50242501
反射、注解总会降低效率, 在Android Studio开发环境下,只需输入一个f 就会智能提示出findviewbyid了,十分方便,而且用插件一键生成,也省事!
更多相关文章
- 一个Demo让你掌握所有的android控件
- Android(安卓)layout xml总结(1)
- android之控件EditText学习
- android时间控件DigitalClock的使用
- android switch 控件自定义样式不显示??
- android:descendantFocusability 焦点 父控件与子控件焦点
- Android(安卓)GLSurfaceView模糊效果
- Android条形统计图实现
- Android(Java):自定义控件