zoukankan      html  css  js  c++  java
  • 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方法就更加简洁,可读性也更好了。

  • 相关阅读:
    直击JDD | 京东技术全景图首次展示 四大重磅智能技术驱动产业未来!
    干货|上云了,如何保障云数据库的高可用?
    直击JDD | 共建智能新城 京东云让城市生活变得简单美好
    2019京东全球科技探索者大会议程抢先曝光!
    京东云入选2019年度TOP100全球软件案例 新一代服务治理框架加速行业落地
    剁手季我做过最牛的事情
    干货|混沌工程落地的六个阶段
    Jenkins 插件中心国内镜像源发布
    list
    queue
  • 原文地址:https://www.cnblogs.com/imfanqi/p/4987648.html
Copyright © 2011-2022 走看看