Android高效率编码-findViewById()的蜕变-注解,泛型,反射

来源:互联网 发布:手机有学编程的吗 编辑:程序博客网 时间:2024/04/29 03:20

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> 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了,十分方便,而且用插件一键生成,也省事!

4 0
原创粉丝点击