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);
    }
}
相关推荐
jinanwuhuaguo36 分钟前
(第三十三篇)五月的文明奠基:OpenClaw 2026.5.2版本的文明级解读
android·java·开发语言·人工智能·github·拓扑学·openclaw
千码君20162 小时前
Trae:一些关于flutter和 go前后端开发构建的分享
android·flutter·gradle·android-studio·trae·vibe code
重生之我是Java开发战士6 小时前
【MySQL】事务 & 用户与权限管理
android·数据库·mysql
怣疯knight8 小时前
Windows不安装 Android Studio如何打包安卓软件
android·windows·android studio
ke_csdn8 小时前
从Java演变到Kotlin下的jet pack
android
wenzhangli78 小时前
在低代码设计中践行 Harness Engineering
android·低代码·rxjava
xingpanvip9 小时前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua
TechMix10 小时前
【fkw学习笔记】Android 13 AOSP 源码添加系统预置应用实战指南
android·笔记·学习
云起SAAS10 小时前
私域直播系统UniApp源码 多商户商城+直播带货 微信小程序+H5+安卓iOS
android·微信小程序·uni-app·私域直播系统
空中海10 小时前
01. 安卓逆向基础、环境搭建与授权
android