The Android calculator you want, it's coming today!

Project directory

1. Project overview

This project mainly realized simple calculator functions, including basic operations of addition, subtraction, multiplication and division, as well as decimal point and clearing functions. It can be regarded as a good example of Android interface and button click event learning. Students who have just used the emulator to display hello world or those who have never been in touch with Android can get started directly.

2. Development environment

The Android version has been adjusted a bit compared to the previous version. It is now 4.2.1. Of course, the version does not affect the code syntax. It's just that gradle has changed. When you import my project, you can change the gradle path.
If you encounter problems, you can refer to these two experiences: How to
quickly solve the Gradle error report
of the Android project How to import Android projects with different gradle versions

Insert picture description here

Three, detailed design

1. Layout design

Before we talk about the layout, let's introduce GridLayout (grid layout) and talk about its advantages:

1. You can set the arrangement of components in the layout yourself
2. You can customize how many rows and columns there are in the grid layout
3. You can directly set the component to be located in a certain row and certain column
4. You can set the component to span several rows or columns

Let's take a look at the layout code of the calculator:

<?xml version="1.0" encoding="utf-8"?>
<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top">
        <!--输入的文本框-->
        <EditText
            android:id="@+id/result"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:hint="请输入数字"
            android:textSize="30dp"/>
    </GridLayout>

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:rowCount="5"
        android:columnCount="4"
        android:layout_gravity="center|top">

        <Button
            android:id="@+id/btn1"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:layout_columnSpan="1"
            android:text="1" />

        <Button
            android:id="@+id/btn2"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="2" />

        <Button
            android:id="@+id/btn3"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="3" />

        <Button
            android:id="@+id/divide"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="/" />

        <Button
            android:id="@+id/btn4"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="4" />

        <Button
            android:id="@+id/btn5"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="5" />
        <Button
            android:id="@+id/btn6"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="6" />
        <Button
            android:id="@+id/multi"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="*" />
        <Button
            android:id="@+id/btn7"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="7"
            />
        <Button
            android:id="@+id/btn8"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="8" />

        <Button
            android:id="@+id/btn9"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="9" />

        <Button
            android:id="@+id/sub"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="—" />

        <Button
            android:id="@+id/btn0"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="0" />

        <Button
            android:id="@+id/point"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:layout_columnSpan="1"
            android:text="." />

        <Button
            android:id="@+id/clean"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:text="del" />

        <Button
            android:id="@+id/plus"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_margin="5dp"
            android:layout_rowSpan="1"
            android:text="+" />

        <Button
            android:id="@+id/equ"
            android:layout_width="390dp"
            android:layout_height="60dp"
            android:layout_columnSpan="4"
            android:layout_margin="5dp"
            android:text="="
            android:textSize="30dp"/>
    </GridLayout>

</GridLayout>

The code is very simple. Each Button has an id, where the "=" button spans a row, and the others are directly added. By default, each component occupies one row and one column.
Another thing to note: we set the component to span multiple rows or columns through android:layout_rowSpan and android:layout_columnSpan; if you want the component to fill the crossed rows or columns, you need to add the following attribute: android:layout_gravity = "fill". Just like the part of the calculator that displays the numbers (result input box).
Let's take a look at the interface preview:

Insert picture description here

2. Main function

2.1, control definition

A lot of buttons are defined, which represent 0-9, addition, subtraction, multiplication, division, decimal point, equal to, and zero. The variable names here must be concise and easy to understand. Do not define variable names at will, and develop a good habit.

    //运算符
    private  Button plus;//加号+
    private  Button sub;//减号-
    private  Button multi; //乘号*
    private  Button divide;// 除号/
    private  Button point; //小数点.
    private  Button equ; //等于=

    private  Button clean;//清除输入框

2.2, control binding

Bind the just-defined variable and the already set control by id, so that the entire variable represents the control. Remember, you must write layout before writing the Main function when writing Android.

        plus = findViewById(R.id.plus);// +
        sub = findViewById(R.id.sub);// -
        multi = findViewById(R.id.multi);// *
        divide = findViewById(R.id.divide); // /
        point = findViewById(R.id.point);//小数点
        equ = findViewById(R.id.equ);//=
        clean = findViewById(R.id.clean);//清空

2.3, control settings listener

Add a click event to each control. This is the most common method. The system listens to your actions and responds.

        plus.setOnClickListener(this);
        sub.setOnClickListener(this);
        multi.setOnClickListener(this);
        divide.setOnClickListener(this);
        equ.setOnClickListener(this);
        point.setOnClickListener(this);
        clean.setOnClickListener(this);

2.4, control settings click event

Here we judge by the variable clear_flag, it is a clear flag, true is cleared, and false is not cleared.
Then classify numbers, operators, and other operations.

public void onClick(View view) {
        //获取文本内容
        String input = editText.getText().toString();
        switch (view.getId()){//选择按钮id
            case R.id.btn0:
            case R.id.btn1:
            case R.id.btn2:
            case R.id.btn3:
            case R.id.btn4:
            case R.id.btn5:
            case R.id.btn6:
            case R.id.btn7:
            case R.id.btn8:
            case R.id.btn9:
            case R.id.point:
                if(clear_flag){
                    clear_flag = false;
                    editText.setText("");//赋值为空
                }
                editText.setText(input + ((Button)view).getText());//结果集就为本身
                break;
            case R.id.plus:
            case R.id.sub:
            case R.id.multi:
            case R.id.divide://加减乘除一起
                if(clear_flag){
                    clear_flag = false;
                    input = "";
                    editText.setText("");
                }
                editText.setText(input + " " + ((Button)view).getText() + " ");
                break;
            case R.id.clean://清除输入框
                if(clear_flag){
                    clear_flag = false;
                    input = "";
                    editText.setText("");
                }else if(input != null || !input.equals("")) {//如果获取到的内容为空
                    editText.setText(input.substring(0, input.length() - 1));//结果集为空
                }
                break;
            case R.id.equ://运算结果等于
                getResult();//调用处理结果集的方法
                break;
        }
    }

2.5, running results

This part of the method is to calculate the result of two numerical operations, which is an if-else statement. equals() is the comparison of two objects. If they are the same, it is true, otherwise it is false. Contains() is the containment relationship, which is true, otherwise it is false. .

 //运算结果的方法
    private void getResult(){
        String exp = editText.getText().toString();//获取文本框的内容
        if(exp==null||exp.equals("")){
            return;
        }
        if(!exp.contains(" ")){
            return;
        }
        if(clear_flag){
            clear_flag = false;
            return;
        }
        clear_flag = true;
        double result = 0;

        //进行截取
        //运算符前的数字
        String s1 = exp.substring(0,exp.indexOf(" "));
        //运算符
        String op = exp.substring(exp.indexOf(" ")+1,exp.indexOf(" ")+2);
        //运算符后的数字
        String s2 = exp.substring(exp.indexOf(" ")+3);

        if(!s1.equals("")&&!s2.equals("")) {//如果包含小数点的运算
            double d1 = Double.parseDouble(s1);//则数字都是double类型
            double d2 = Double.parseDouble(s2);
            if (op.equals("+")) {//如果是 +
                result = d1 + d2;
            } else if (op.equals("-")) {
                result = d1 - d2;
            } else if (op.equals("*")) {
                result = d1 * d2;
            } else if (op.equals("/")) {
                if (d2 == 0) { //如果被除数是0
                    result = 0; //则结果是0
                }
                else {//否则执行正常是除法运算
                    result = d1 / d2;
                }
            }

            if (!s1.contains(".") && !s2.contains(".") && !op.equals("/")) {//如果是整数类型
                int r = (int) result; //都是整形
                editText.setText(r + "");
            } else{
                editText.setText(result + "");
            }
        }else if(!s1.equals("") && s2.equals("")){//如果是只输入运算符前的数
            editText.setText(exp);//直接返回当前文本框的内容
        }else if(s1.equals("") && !s2.equals("")){//如果是只输入运算符后面的数
            double d2 = Double.parseDouble(s2);

            //运算符前没有输入数字
            if (op.equals("+")) {
                result = 0 + d2;
            } else if (op.equals("-")) {
                result = 0 - d2;
            } else if (op.equals("*")) {
                result = 0;
            } else if (op.equals("/")) {
                result = 0;
            }

            if (!s1.contains(".") && !s2.contains(".")) {
                int r = (int) result;
                editText.setText(r + "");
            } else{
                editText.setText(result + "");
            }
        }else {
            editText.setText("");
        }
    }

4. Project effect

1. Open the simulator to run, enter two numbers

Insert picture description here


2. Press the equal key to get the result

Insert picture description here


3. Select the clear key to clear all the results

Insert picture description here

Five, project summary

This project is a relatively basic example to test the layout and controls. It is a very good example for beginners. It can be used as the second example after Hello World. After carefully digesting the contents, it will be very fast in the future.

Six, source code download

Students who need to learn the source code can follow my WeChat official account and reply: Calculator , you can get the source code for free, and there are more free Android projects waiting for you to learn. I give you a well-organized Android learning collection : Android project and Android tutorial summary (epic collection)