Android开发案例——简单计算器

实现计算机的简单功能

1、显示页面jsj.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#eee">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#42714A"
        android:gravity="center_vertical"
        android:text="Chapter03"
        android:textColor="#fff"
        android:textSize="25sp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="简单计算机"
        android:gravity="center_horizontal"
        android:textSize="20sp"
        android:textColor="#000"/>
    <TextView
        android:id="@+id/tvresult"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:background="#fff"
        android:layout_margin="5dp"
        android:text="0"
        android:textSize="40sp"
        android:textStyle="bold"
        android:textColor="#000"
        android:gravity="bottom|right"/>
    <GridLayout
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="4">
        <Button
            android:id="@+id/btn_ce"
            style="@style/MyTextStyle"
            android:text="CE"
            />
        <Button
            android:id="@+id/btn_divide"
            style="@style/MyTextStyle"
            android:text="÷"
            />

        <Button
            android:id="@+id/btn_multiply"
            style="@style/MyTextStyle"
            android:text="x" />
        <Button
            android:id="@+id/btn_c"
            style="@style/MyTextStyle"
            android:text="C"
            />
        <Button
            android:id="@+id/btn_7"
            style="@style/MyTextStyle"
            android:text="7"
            />
        <Button
            android:id="@+id/btn_8"
            style="@style/MyTextStyle"
            android:text="8"
            />
        <Button
            android:id="@+id/btn_9"
            style="@style/MyTextStyle"
            android:text="9"
            />
        <Button
            android:id="@+id/btn_plus"
            style="@style/MyTextStyle"
            android:text="+"
            />
        <Button
            android:id="@+id/btn_4"
            style="@style/MyTextStyle"
            android:text="4"
            />
        <Button
            android:id="@+id/btn_5"
            style="@style/MyTextStyle"
            android:text="5"
            />
        <Button
            android:id="@+id/btn_6"
            style="@style/MyTextStyle"
            android:text="6"
            />
        <Button
            android:id="@+id/btn_minus"
            style="@style/MyTextStyle"
            android:text="---"
            />
        <Button
            android:id="@+id/btn_1"
            style="@style/MyTextStyle"
            android:text="1"
            />
        <Button
            android:id="@+id/btn_2"
            style="@style/MyTextStyle"
            android:text="2"
            />
        <Button
            android:id="@+id/btn_3"
            style="@style/MyTextStyle"
            android:text="3"
            />
        <Button
            android:id="@+id/btn_sqrt"
            style="@style/MyTextStyle"
            android:text="√"
            />
        <Button
            android:id="@+id/btn_reciprocal"
            style="@style/MyTextStyle"
            android:text="1/X"
            />

        <Button
            android:id="@+id/btn_0"
            style="@style/MyTextStyle"
            android:text="0" />
        <Button
            android:id="@+id/btn_dot"
            style="@style/MyTextStyle"
            android:text="."
            />
        <Button
            android:id="@+id/btn_equal"
            style="@style/MyTextStyle"
            android:text="="
            />
    </GridLayout>
</LinearLayout>

2、样式页面 style.xml

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyTextStyle">
        <item name="android:textSize">23sp</item>
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">80dp</item>
        <item name="android:layout_columnWeight">1</item>
    </style>

</resources>

3、后端代码CalculatorActivity.java

java 复制代码
package com.example.android;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.DecimalFormat;

public class CalculatorActivity extends AppCompatActivity {

    private TextView tvResult; //用于显示计算结果和输入表达式的控件
    private String currentInput = "0"; //初始值为0
    private String operator = ""; //当前选择的运算符,初始为空字符串
    private double firstNumber = 0; //存储第一个操作数,初始值为0
    private boolean isNewNumber = true; //标记是否开始输入新的数字,初始为true

    @Override     //活动创建时调用的方法
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jsj); //活动布局界面

        tvResult = findViewById(R.id.tvresult); //获取对象

        int[] buttonIds = {
                R.id.btn_ce, R.id.btn_divide, R.id.btn_multiply, R.id.btn_c,
                R.id.btn_7, R.id.btn_8, R.id.btn_9, R.id.btn_plus,
                R.id.btn_4, R.id.btn_5, R.id.btn_6, R.id.btn_minus,
                R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_sqrt,
                R.id.btn_reciprocal, R.id.btn_0, R.id.btn_dot, R.id.btn_equal
        };  //存储所有按钮的id

        for (int id : buttonIds) { //为每个按钮设置点击事件监听器
            Button button = findViewById(id);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    handleButtonClick(((Button) v).getText().toString()); //调用handleButtonClick方法
                }
            });
        }
    }

    private void handleButtonClick(String buttonText) {
        switch (buttonText) {
            case "CE":
                currentInput = "0";
                break;
            case "C":
                currentInput = "0";
                operator = "";
                firstNumber = 0;
                isNewNumber = true;
                break;  //恢复初始状态
            case "÷":
            case "x":
            case "+":
            case "---":
                if (!operator.isEmpty()) {
                    calculateResult(); //如果存在运算符,调用calculateResult方法
                }
                operator = buttonText;
                firstNumber = Double.parseDouble(currentInput);
                isNewNumber = true;
                break;
            case "=": //调用calculateResult方法计算结果,清空operator
                calculateResult();
                operator = "";
                isNewNumber = true;
                break;
            case "√":
                double sqrtResult = Math.sqrt(Double.parseDouble(currentInput));
                currentInput = formatResult(sqrtResult);
                break;
            case "1/X":
                if (!currentInput.equals("0")) { //分母不能为0
                    double reciprocalResult = 1 / Double.parseDouble(currentInput);
                    currentInput = formatResult(reciprocalResult);
                } else {
                    currentInput = "错误";
                }
                break;
            case ".":
                if (isNewNumber) { //如果是新数字,currentInput设置为0
                    currentInput = "0.";
                    isNewNumber = false;
                } else if (!currentInput.contains(".")) {
                    currentInput += "."; //如果不包含.则在后面追加.
                }
                break;
            default:
                if (isNewNumber) {
                    currentInput = buttonText;
                    isNewNumber = false;
                } else {
                    currentInput += buttonText;
                }
                break;
        }
        tvResult.setText(currentInput); //将值设置到tvResult中显示
    }

    private void calculateResult() {
        double secondNumber = Double.parseDouble(currentInput); //将输入内容转换成double型
        double result = 0;
        switch (operator) {
            case "÷":
                if (secondNumber != 0) { //如果除数不为0
                    result = firstNumber / secondNumber;
                } else {
                    currentInput = "错误";
                    return;
                }
                break;
            case "x":
                result = firstNumber * secondNumber;
                break;
            case "+":
                result = firstNumber + secondNumber;
                break;
            case "---":
                result = firstNumber - secondNumber;
                break;
        }
        currentInput = formatResult(result); //将结果赋值给currentInput
    }

    private String formatResult(double result) { //格式化
        DecimalFormat decimalFormat = new DecimalFormat("#.########");
        return decimalFormat.format(result);
    }
}
相关推荐
sweetying2 小时前
30了,人生按部就班
android·程序员
用户2018792831672 小时前
Binder驱动缓冲区的工作机制答疑
android
真夜2 小时前
关于rngh手势与Slider组件手势与事件冲突解决问题记录
android·javascript·app
用户2018792831672 小时前
浅析Binder通信的三种调用方式
android
用户093 小时前
深入了解 Android 16KB内存页面
android·kotlin
火车叼位4 小时前
Android Studio与命令行Gradle表现不一致问题分析
android
前行的小黑炭6 小时前
【Android】 Context使用不当,存在内存泄漏,语言不生效等等
android·kotlin·app
前行的小黑炭7 小时前
【Android】CoordinatorLayout详解;实现一个交互动画的效果(上滑隐藏,下滑出现);附例子
android·kotlin·app
用户20187928316719 小时前
Android黑夜白天模式切换原理分析
android
芦半山19 小时前
「幽灵调用」背后的真相:一个隐藏多年的Android原生Bug
android