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

多行变一行

比如说开发一个简单的计算器应用程序,需要定义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方法就更加简洁,可读性也更好了。

原文地址:https://www.cnblogs.com/imfanqi/p/4987648.html