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

本文介绍如何通过优化代码结构来简化Android计算器应用的实现过程,包括将数字按钮合并到一行、提炼函数以减少重复代码、增强代码可读性和维护性。通过使用Android Studio的提炼函数功能,开发者可以更高效地组织代码,提高开发效率。

多行变一行

比如说开发一个简单的计算器应用程序,需要定义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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值