Andriod学习笔记1:代码优化总结1

多行变一行

好比说开发一个简单的计算器应用程序,须要定义0-9的数字按钮,第一次就习惯性地写出了以下代码:java

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的方法中进行赋值,一般写法以下:blog

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 提供了很是好的提炼函数的操做。it

选中以上代码,右键菜单或者顶部菜单中依次选择“Refactor”->"Extract"->"Method"io

而后在弹出的对话框中输入“initButton”,点击肯定class

这堆代码对被一行代码取代了:程序

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方法就更加简洁,可读性也更好了。

相关文章
相关标签/搜索