Andriod学习笔记1:代码优化总结1
2015-11-23 10:35
232 查看
多行变一行
比如说开发一个简单的计算器应用程序,需要定义0-9的数字按钮,第一次就习惯性地写出了如下代码:Button btn0; Button btn1; Button btn2; Button btn3; Button btn4; Button btn5; Button btn6; Button btn7; Button btn8; Button btn9;
其中这种 写法占用的屏幕空间很大,可读性并不好,我们可以优化成一行:
Button btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9;
这种同一类控件写在一行,看起来就简洁很多了。
提炼函数
定义好数字按钮之后,我们就需要在OnCreate的方法中进行赋值,通常写法如下:btn0 = (Button) findViewById(R.id.btn0); btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); btn3 = (Button) findViewById(R.id.btn3); btn4 = (Button) findViewById(R.id.btn4); btn5 = (Button) findViewById(R.id.btn5); btn6 = (Button) findViewById(R.id.btn6); btn7 = (Button) findViewById(R.id.btn7); btn8 = (Button) findViewById(R.id.btn8); btn9 = (Button) findViewById(R.id.btn9);
这样写也还好,不错我们还是可以优化一下的。
Andriod Studio 提供了非常好的提炼函数的操作。
选中以上代码,右键菜单或者顶部菜单中依次选择“Refactor”->"Extract"->"Method"
然后在弹出的对话框中输入“initButton”,点击确定
这堆代码对被一行代码取代了:
initButton();
Andriod Studio会自动将这堆代码提炼成initButton()方法:
private void initButton() {
btn0 = (Button) findViewById(R.id.btn0); btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); btn3 = (Button) findViewById(R.id.btn3); btn4 = (Button) findViewById(R.id.btn4); btn5 = (Button) findViewById(R.id.btn5); btn6 = (Button) findViewById(R.id.btn6); btn7 = (Button) findViewById(R.id.btn7); btn8 = (Button) findViewById(R.id.btn8); btn9 = (Button) findViewById(R.id.btn9);}
运用提炼函数之后,onCreate方法就更加简洁,可读性也更好了。
相关文章推荐
- Ajax+PHP+MySQL 登陆示例
- GOOGLE地图街景预览默认的退出按扭显示
- 在 ASP.NET MVC 中使用 HTML Helpers 的那些事
- php手记-list()
- Windows下Qt的MySQL驱动编译方法及异常错误解决方案
- CPP11中的atomic类以及memory_order
- c++学习(四)
- JAVA编程相关:eclipse如何导入已有工程
- 时间格式化 java js mysql
- 轻松学习C#的读写操作
- JAVA wait(), notify(),sleep详解
- java字符串与16进制2进制互转
- Caused by: java.lang.IllegalArgumentException: Can't use FLAG_RECEIVER_BOOT_UPGRADE here的解决
- 使用JavaMail接收邮件的示例
- selenium python (一) 开发环境搭建
- Jenkins中Git Plugin配置的几个小问题
- 读《C专家编程》笔记-关于内存泄漏
- CircleImg.java自定义圆形图
- java项目案例 java项目源码 java后台框架源码 企业级 SpringMVC mybatis or hibernate
- WIN7 系统代码页异常