Android calculator implementation

1. Project Overview

This project is a simple calculator application that can perform the basic functions of a calculator such as addition, subtraction, multiplication, and division. We will use Android Studio as the development tool.

2. Project design

1. Create a new Android project in Android Studio.
2. In the layout file (`activity_main.xml`) we will add a button and a text view to display the results.
3. In the code file (`MainActivity.java`), we will process the user's input and display the calculation results.

3. Project development

1. Layout file

Implement the front-end page effect in the layout file `activity_main.xml`. Use components such as `EditText` for entering procedures and results, and `Button` for performing calculations.

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

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:columnCount="1"
        android:orientation="vertical"
        android:rowCount="2">

        <EditText
            android:id="@+id/mresult"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:enabled="false"
            android:hint="这里显示结果"
            android:textColor="@color/black" />


        <EditText
            android:id="@+id/mjsgc"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:hint="这里显示计算过程" />
    </GridLayout>

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|top"
        android:orientation="horizontal"

        android:columnCount="4"
        android:rowCount="5"
        >

        <Button
            android:id="@+id/btnqc"
            android:layout_width="180dp"
            android:layout_height="60dp"
            android:layout_columnSpan="2"
            android:text="C" />

        <Button
            android:id="@+id/btndel"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:layout_columnSpan="1"
            android:text="del" />

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

        <Button
            android:id="@+id/btn7"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:text="7" />

        <Button
            android:id="@+id/btn8"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:text="8" />

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

        <Button
            android:id="@+id/btnx"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:text="*" />


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

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

        <Button
            android:id="@+id/btn6"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:text="6" />

        <Button
            android:id="@+id/btnj"
            android:layout_width="90dp"
            android:layout_height="63dp"
            android:text="-" />

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

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

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


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

        <Button
            android:id="@+id/zhengfu"
            android:layout_width="90dp"
            android:layout_height="60dp"
            android:text="预留" />

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

        <Button
            android:id="@+id/btnd"
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:text="." />


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

        <Space />
    </GridLayout>

</GridLayout>

GridLayout layout: If you want to achieve the layout effect of row merging, using GridLayout layout is the simplest and easiest way to achieve it.

Common attributes: android:orientation sets the horizontal or vertical display        android:columnCount sets the number of columns android:rowCount sets the number of rows

Child control attributes: android:layout_rowSpan merges several columns vertically across   android:layout_columSpan merges several rows horizontally        android:layout_gravityThe position of the parent component

 The picture above is the effect of the front-end page

2. Code files

In the code file `MainActivity.java` we will add a click event listener for the button, process user input, and display the calculation results.

package com.example.a4_11;


import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //显式结果和计算过程
    private EditText mresult, mjsgc;
    //数字0-9
    private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0;
    private Button btnd; //小数点
    //运算符
    private Button btn1j, btnj, btnx, btnc, btn1d; //加减乘除等于

    //功能键
    private Button btndel, btnqc;//回退键和清除所有键
    boolean equals_flag = false;//等号标识

    boolean del_flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //数字0-9
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn4 = findViewById(R.id.btn4);
        btn5 = findViewById(R.id.btn5);
        btn6 = findViewById(R.id.btn6);
        btn7 = findViewById(R.id.btn7);
        btn8 = findViewById(R.id.btn8);
        btn9 = findViewById(R.id.btn9);
        btn0 = findViewById(R.id.btn0);
        //运算符
        btn1j = findViewById(R.id.btn1j);// +
        btnj = findViewById(R.id.btnj);// -
        btnx = findViewById(R.id.btnx);// *
        btnc = findViewById(R.id.btnc); // /
        btnd = findViewById(R.id.btnd);//小数点
        btn1d = findViewById(R.id.btn1d);// =

        btndel = findViewById(R.id.btndel);//退回
        btnqc = findViewById(R.id.btnqc);//清除

        mresult = findViewById(R.id.mresult);//结果框
        mjsgc = findViewById(R.id.mjsgc);//输入过程框

        //点击事件0-9
        btn0.setOnClickListener(this);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
        btn6.setOnClickListener(this);
        btn7.setOnClickListener(this);
        btn8.setOnClickListener(this);
        btn9.setOnClickListener(this);
        btnd.setOnClickListener(this);
        //点击事件运算符
        btn1j.setOnClickListener(this);
        btnj.setOnClickListener(this);
        btnx.setOnClickListener(this);
        btnc.setOnClickListener(this);
        btn1d.setOnClickListener(this);

        btndel.setOnClickListener(this);
        btnqc.setOnClickListener(this);
    }

    //读取每个按钮的点击的内容
    @Override
    public void onClick(View v) {
        //获取输入框和结果框的内容
        String input = mjsgc.getText().toString();
        String output = mresult.getText().toString();
        switch (v.getId()) {
            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.btnd:
                if (equals_flag) {
                    //按过等号之后,重新点数字们
                    equals_flag = false;
                    mjsgc.setText(((Button) v).getText());
                    mresult.setText(((Button) v).getText());
                } else {
                    mjsgc.setText(input + ((Button) v).getText());
                    mresult.setText(((Button) v).getText());
                }
                break;
            case R.id.btn1j:
            case R.id.btnj:
            case R.id.btnx:
            case R.id.btnc:
                if (equals_flag) {
                    //按过等号之后,重新点数字
                    equals_flag = false;
                    mjsgc.setText(output + " " + ((Button) v).getText() + " ");
                } else {
                    mjsgc.setText(input + " " + ((Button) v).getText() + " ");
                }
                break;
            case R.id.btndel:
                equals_flag = false;
                if (input.length() > 0) {//如果获取到的内容不为空
                    mjsgc.setText(input.substring(0, input.length() - 1));
                } else {
                    mresult.setText(null);
                    mjsgc.setText(null);
                }
                break;
            case R.id.btnqc:
                mresult.setText(null);
                mjsgc.setText(null);
                break;
            case R.id.btn1d://运算结果  =
                getResult();//调用处理结果集的方法
                break;
        }
    }

    //运算结果的方法
    public void getResult() {
        try {
            String JSGC = mjsgc.getText().toString();//获取计算过程文本框的内容
            double dResult = 0;
            int iResult = 0;

            //如果直接点等号
            if (JSGC.equals("") || JSGC == null) {
                return;
            }
            if (equals_flag) {
                equals_flag = false;
                return;
            }
            equals_flag = true;//点击过等号之后,标识亮起

            String s1, s2, op;

            //运算符前的数字
            s1 = JSGC.substring(0, JSGC.indexOf(" "));
            //运算符
            op = JSGC.substring(JSGC.indexOf(" ") + 1, JSGC.indexOf(" ") + 2);
            //运算符后的数字
            s2 = JSGC.substring(JSGC.indexOf(" ") + 3);

            double d1, d2;
            //s1转化成double型
            if (!s1.equals("")) {
                if (s1.charAt(0) == '.') {
                    s1 = "0" + s1;//如果简写小数(如0.03简写.03,需要帮它完整输出数字)
                }
                d1 = Double.parseDouble(s1);//正常转化
            } else {
                d1 = 0;//如果首次只输入了“运算符 数字”,如: + 4,则返回:0 + 4
                mjsgc.setText("0" + JSGC);
            }

            //s2转化成double型
            if (!s2.equals("")) {
                if (s2.charAt(0) == '.') {
                    s2 = "0" + s2;
                }
                d2 = Double.parseDouble(s2);
            } else {
                d2 = d1;
                if (s1.equals("")) {
                    mjsgc.setText("0" + JSGC + "0");//如果只输入了运算符,如 + ,输出0 + 0,得结果0
                } else {
                    mjsgc.setText(JSGC + s1);//如果不输入s2,如,9 * ,输出9 * 9 ,得结果81
                }
            }


            if (op.equals("+")) {//如果是 +
                dResult = d1 + d2;
            } else if (op.equals("-")) {
                dResult = d1 - d2;
            } else if (op.equals("*")) {
                dResult = d1 * d2;
            } else if (op.equals("/")) {
                if (d2 == 0) { //如果被除数是0
                    Toast.makeText(this, "除数不能为0", Toast.LENGTH_SHORT).show();
                    return;
                } else {//否则执行正常是除法运算
                    dResult = d1 / d2;
                }
            }


            if (s1.contains(".") || s2.contains(".") || op.equals("/")) {
                mresult.setText(dResult + "");//如果是小数、或者除法运算
            } else {
                iResult = (int) dResult; //否则都是整型
                mresult.setText(iResult + "");
            }

        } catch (Exception e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
            Log.i("JSQ", e.toString());
        }

    }
}

3. Run the project

Click the run button to run successfully.

Operation renderings 

3. Experience

1. Understand layout design

Understanding how to design and implement a calculator user interface is an important step. I need to think about how to place various controls (like text boxes, buttons, etc.) on the screen for the best user experience.

2. Understand Android event handling

When users perform operations on the calculator (such as clicking buttons or entering numbers), corresponding event processing logic is required to respond to these operations. This involves understanding Android's event handling mechanism, such as click events, input events, etc.

3. Learning and innovation

Developing Android calculators made me understand that it is necessary to learn new technologies and knowledge, but more importantly, it is to be able to apply this knowledge to actual problems and innovate. This process gave me a new understanding of learning.

4. Understand Android data storage

In this project, I need to store some data in the app, such as numbers and actions entered by the user. I need to understand how to achieve this using Android's data storage technology.

5. Debugging and testing

During the development process, I need to spend a lot of time debugging and testing to ensure that the calculator functions properly and the user interface is friendly. This taught me the importance of testing and how to write effective test cases to find and fix bugs.

4. Summary

In this project, I learned how to implement the calculator function in an Android application. How to create and manage views in Activity. Learn how to use XML layout files to design and layout interfaces. Requires familiarity with various layout elements such as `GridLayout` . Learn how to use various UI components to achieve user interaction. This includes how to use components such as `EditText`, `Button`, `TextView`, etc. to enter and display text. When implementing the calculator function, you need to understand the rules and algorithms of various operations. This includes the basic principles of addition, subtraction, multiplication and division, as well as how to deal with complex expressions such as floating point numbers and parentheses. Can master the basic concepts of Android application development, including layout, event handling and calculation functions. This will lay a solid foundation for further learning in the field of Android development.

Guess you like

Origin blog.csdn.net/m0_72104085/article/details/131307062