【Android应用开发之前端——简单计算器效果】

article/2025/9/19 9:11:56

1.完成计算器布局

整个计算器界面主要分为两部分,一部分是上面的文本框,用于显示计算结果;另一部分是下面的几排按钮,用户输入数字与各种运算符。为了减少复杂度,我们可以精简一些功能,只保留数字与加、减、乘、除四则运算,另外补充一个开根号(求平方根)的运算。至于App的显示界面,基本与习惯的计算器界面保持一致,经过对操作按钮的适当排列,调整后的设计效果如下图所示:在这里插入图片描述
完成此界面用到了以下控件:
● 线性布局LinearLayout:计算器界面整体上是从上往下布局的,所以需要垂直方向的LinearLayout;下面部分每行都有4个按钮,又需要水平方向的LinearLayout。
● 滚动视图ScrollView:虽然计算器界面不宽也不高,但是以防万一,最好还是加个垂直方向的ScrollView。
● 文本视图TextView:很明显上方标题“简单计算器”就是TextView,下面的计算结果也需要使用TextView,而且是能够自动从下往上滚动的TextView,可参考前文聊天室效果的文本视图。
● 按钮Button:绝大多数数字与运算符按钮都采用Button控件。
● 图像按钮ImageButton:开根号的运算符“√”虽然能够打出来,但是右上角少了一横,所以该按钮要用一张标准的开根号图片显示,这就用到了ImageButton。
● 九宫格图片:注意计算器界面左下角的“0”,该按钮是其他按钮的两倍宽,如果使用普通图片当背景,势必会造成边缘线被拉宽、拉模糊的问题。故而要采用点九图片避免这种问题。

布局具体实现如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_height="match_parent"android:layout_width="match_parent"android:orientation="vertical"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center"android:textSize="30sp"android:text="简单计算器" /><TextViewandroid:id="@+id/tv_result"android:layout_width="match_parent"android:layout_height="200dp"android:scrollbars="vertical"android:textSize="25sp"android:background="@drawable/textview_border"/><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:orientation="horizontal"><Buttonandroid:text="CE"android:id="@+id/btn_cancel"style="@style/btn_cal" /><Buttonandroid:text="÷"android:id="@+id/btn_divide"style="@style/btn_cal" /><Buttonandroid:text="×"android:id="@+id/btn_multiply"style="@style/btn_cal" /><Buttonandroid:text="C"android:id="@+id/btn_clear"style="@style/btn_cal" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:orientation="horizontal"><Buttonandroid:text="7"android:id="@+id/btn_seven"style="@style/btn_cal" /><Buttonstyle="@style/btn_cal"android:id="@+id/btn_eight"android:text="8" /><Buttonandroid:text="9"android:id="@+id/btn_nine"style="@style/btn_cal" /><Buttonandroid:text="+"android:id="@+id/btn_plus"style="@style/btn_cal" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:orientation="horizontal"><Buttonandroid:text="4"android:id="@+id/btn_four"style="@style/btn_cal" /><Buttonstyle="@style/btn_cal"android:id="@+id/btn_five"android:text="5" /><Buttonandroid:text="6"android:id="@+id/btn_six"style="@style/btn_cal" /><Buttonandroid:text="-"android:id="@+id/btn_minus"style="@style/btn_cal" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:orientation="horizontal"><Buttonandroid:text="1"android:id="@+id/btn_one"style="@style/btn_cal" /><Buttonstyle="@style/btn_cal"android:id="@+id/btn_two"android:text="2" /><Buttonandroid:text="3"android:id="@+id/btn_three"style="@style/btn_cal" /><ImageButtonandroid:id="@+id/btn_sqrt"android:src="@drawable/radical"android:scaleType="centerInside"style="@style/btn_cal" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:orientation="horizontal"><Buttonandroid:text="0"android:id="@+id/btn_zero"android:layout_weight="2"style="@style/btn_cal" /><Buttonandroid:text="."android:id="@+id/btn_dot"style="@style/btn_cal" /><Buttonandroid:text="="android:id="@+id/btn_equal"style="@style/btn_cal" /></LinearLayout>
</LinearLayout>

2.设置按钮风格、背景图片等

给按钮统一样式:

<?xml version="1.0" encoding="utf-8"?>
<resources><style name="btn_cal"><item name="android:layout_width">0dp</item><item name="android:layout_height">match_parent</item><item name="android:layout_weight">1</item><item name="android:gravity">center</item><item name="android:textColor">@color/black</item><item name="android:textSize">30sp</item><item name="android:background">@drawable/btn_bg</item><item name="android:top">3dp</item><item name="android:left">3dp</item><item name="android:right">3dp</item><item name="android:bottom">3dp</item></style>
</resources>

为计算结果框设置边框

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"><item android:left="-1dp" android:right="-1dp"> <!--消除左边框和右边框--><shape  android:shape="rectangle" ><solid android:color="#FFFFFF" /><stroke android:width="1dp" android:color="#000000"/></shape></item>
</layer-list>

3.完成计算器功能

package com.example.exercise;import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.math.BigDecimal;class Arith {//默认除法运算精度private static final int DEF_DIV_SCALE = 10;//构造器私有,让这个类不能实例化private Arith(){}//提供精确的加法运算public static double add(double v1,double v2){BigDecimal b1 = BigDecimal.valueOf(v1);BigDecimal b2 = BigDecimal.valueOf(v2);return b1.add(b2).doubleValue();}//提供精确的减法运算public static double sub(double v1,double v2){BigDecimal b1 = BigDecimal.valueOf(v1);BigDecimal b2 = BigDecimal.valueOf(v2);return b1.subtract(b2).doubleValue();}//提供精确的乘法运算public static double mul(double v1,double v2){BigDecimal b1 = BigDecimal.valueOf(v1);BigDecimal b2 = BigDecimal.valueOf(v2);return b1.multiply(b2).doubleValue();}//提供精确的除法运算public static double div(double v1,double v2){BigDecimal b1 = BigDecimal.valueOf(v1);BigDecimal b2 = BigDecimal.valueOf(v2);return b1.divide(b2).doubleValue();}
}public class CalculatorActivity extends AppCompatActivity implements View.OnClickListener{private String operator = ""; //操作符private String firstNum = ""; //前一个操作数private String nextNum = ""; //后一个操作数private String result = ""; // 当前计算结果private String showText = ""; //显示的文本内容private TextView tv_result;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_calculator);tv_result = findViewById(R.id.tv_result);findViewById(R.id.btn_cancel).setOnClickListener(this);findViewById(R.id.btn_clear).setOnClickListener(this);findViewById(R.id.btn_equal).setOnClickListener(this);findViewById(R.id.btn_sqrt).setOnClickListener(this);findViewById(R.id.btn_divide).setOnClickListener(this);findViewById(R.id.btn_dot).setOnClickListener(this);findViewById(R.id.btn_eight).setOnClickListener(this);findViewById(R.id.btn_four).setOnClickListener(this);findViewById(R.id.btn_minus).setOnClickListener(this);findViewById(R.id.btn_multiply).setOnClickListener(this);findViewById(R.id.btn_nine).setOnClickListener(this);findViewById(R.id.btn_one).setOnClickListener(this);findViewById(R.id.btn_plus).setOnClickListener(this);findViewById(R.id.btn_seven).setOnClickListener(this);findViewById(R.id.btn_six).setOnClickListener(this);findViewById(R.id.btn_three).setOnClickListener(this);findViewById(R.id.btn_two).setOnClickListener(this);findViewById(R.id.btn_zero).setOnClickListener(this);findViewById(R.id.btn_five).setOnClickListener(this);}public void onClick(View v) {int resid = v.getId();String inputText;if (resid == R.id.btn_sqrt) {inputText = "√";} else {inputText = ((TextView) v).getText().toString();}Log.d("sqrt", "resid=" + resid + ",inputText=" + inputText);if (resid == R.id.btn_clear) {clear("0");} else if (resid == R.id.btn_cancel) {if (operator.equals("=") == true){Toast.makeText(this, "没有可取消的数字了", Toast.LENGTH_SHORT).show();return;}if (operator.equals("") == true) {if (firstNum.length() == 1) {firstNum = "0";} else if (firstNum.length() > 0) {firstNum = firstNum.substring(0, firstNum.length() - 1);} else if (showText == "0") {firstNum = "0";} else {Toast.makeText(this, "没有可取消的数字了", Toast.LENGTH_SHORT).show();}showText = firstNum;tv_result.setText(showText);} else {if (nextNum.length() == 1) {nextNum = "";} else if (nextNum.length() > 0) {nextNum = nextNum.substring(0, nextNum.length() - 1);} else {Toast.makeText(this, "没有可取消的数字了", Toast.LENGTH_SHORT).show();return;}showText = showText.substring(0, showText.length() - 1);tv_result.setText(showText);}} else if (resid == R.id.btn_equal) {if (operator.length() == 0 || operator.equals("=") == true) {Toast.makeText(this, "请输入运算符", Toast.LENGTH_SHORT).show();return;} else if (nextNum.length() <= 0) {Toast.makeText(this, "请输入数字", Toast.LENGTH_SHORT).show();return;}if(operator == "√"){if(convertToDouble(firstNum) < 0){Toast.makeText(this, "开根号的数值不能小于0", Toast.LENGTH_SHORT).show();return;}result = String.valueOf(Math.sqrt(convertToDouble(firstNum)));if((result.substring(result.length() - 2, result.length() - 1).equals(".") == true) && (result.substring(result.length() - 1).equals("0") == true)){result = result.substring(0, result.length() - 2);}operator = inputText;showText = showText + "=" + result;tv_result.setText(showText);} else if (calculate() == true) {operator = inputText;showText = showText + "=" + result;tv_result.setText(showText);} else {return;}} else if(resid == R.id.btn_minus){if(operator.length() == 0 || operator.equals("=") == true || operator.equals("√") == true){operator = inputText;showText = showText + operator;tv_result.setText(showText);} else if(operator.length() == 1) {operator = inputText;showText = showText.substring(0, showText.length()-1) + operator;tv_result.setText(showText);}else{Toast.makeText(this, "请输入数字", Toast.LENGTH_SHORT).show();return;}} else if(resid == R.id.btn_plus || resid == R.id.btn_divide || resid == R.id.btn_multiply){if(firstNum.length() <= 0){Toast.makeText(this, "请输入数字", Toast.LENGTH_SHORT).show();return;}if(operator.length() == 0 || operator.equals("=") == true || operator.equals("√") == true){operator = inputText;showText = showText + operator;tv_result.setText(showText);} else if(operator.length() == 1) {operator = inputText;showText = showText.substring(0, showText.length()-1) + operator;tv_result.setText(showText);}else{Toast.makeText(this, "请输入数字", Toast.LENGTH_SHORT).show();return;}} else if(resid == R.id.btn_sqrt){if(showText == "0" || firstNum.equals("0") == true){firstNum = showText = "";}operator = inputText;showText = showText + operator;tv_result.setText(showText);} else{if(operator.equals("=") == true){operator = "";firstNum = "";showText = "";}if(operator.equals("√")){firstNum = firstNum + inputText;nextNum = "";}if(resid == R.id.btn_dot){inputText = ".";}if(operator.equals("") == true){if(showText == "0" || firstNum.equals("0") == true){firstNum = showText = "";}firstNum = firstNum + inputText;} else {nextNum = nextNum + inputText;}showText = showText + inputText;tv_result.setText(showText);}}private double convertToDouble(String number){return Double.parseDouble(number);}private boolean calculate() {if (operator.equals("+") == true) {result = String.valueOf(Arith.add(convertToDouble(firstNum), convertToDouble(nextNum)));} else if (operator.equals("-") == true) {result = String.valueOf(Arith.sub(convertToDouble(firstNum), convertToDouble(nextNum)));} else if (operator.equals("×") == true) {result = String.valueOf(Arith.mul(convertToDouble(firstNum), convertToDouble(nextNum)));} else if (operator.equals("÷") == true) {if ("0".equals(nextNum)) {Toast.makeText(this, "被除数不能为零", Toast.LENGTH_SHORT).show();return false;} else {result = String.valueOf(Arith.div(convertToDouble(firstNum), convertToDouble(nextNum)));}}if((result.substring(result.length() - 2, result.length() - 1).equals(".") == true) && (result.substring(result.length() - 1).equals("0") == true)){result = result.substring(0, result.length() - 2);}firstNum = result;nextNum = "";return true;}private void clear(String text){showText = text;tv_result.setText(showText);operator = "";firstNum = "0";nextNum = "";result = "";}
}

整体效果如下:

在这里插入图片描述


http://chatgpt.dhexx.cn/article/J8g1MnGK.shtml

相关文章

使用Android 实现计算器功能

使用android实现简易的计算器的功能 1、给计算机布局&#xff1a;activity_main_xml&#xff1a; <?xml version"1.0" encoding"utf-8"?> <GridLayout xmlns:android"http://schemas.android.com/apk/res/android"xmlns:app"h…

android studio实现计算器界面

实现计算器界面 新建项目1、打开Android Studio2、创建项目3、设置项目基本信息4、等待项目文件加载 打开界面文件1、设置线性布局2、增加子容器3、添加内容 计算器界面完成效果 新建项目 1、打开Android Studio 2、创建项目 点击右上角【New Project】选择“Empty Activity”…

Android Studio实现计算器功能

实验一&#xff1a;做一个简单的计算器 1.创建布局文件Activity_main.xml 代码如下&#xff1a; <?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://schemas.android.com/apk/res/android"android:orient…

Android Studio入门教程(计算器)

一、建立开发环境 1、AS简介 Android Studio 是Google开发的一款面向Android开发者的IDE&#xff0c;支持Windows、Mac、Linux等操作系统&#xff0c;基于流行的开发语言java集成开发环境IntelliJ搭建而成的&#xff0c;类似Eclipse ADT。该IDE在2003年5月的Google I/O开发者…

Android开发——简单计算器实现

计算器项目&#xff0c;要求实现加、减、乘、除、求倒数、求平方根等简单运算。 真机调试结果如下图&#xff1a; 布局文件&#xff1a;main_activity.xml <?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://sc…

Android Studio简易计算器

目录 第一步&#xff0c;创建新项目 第二步&#xff0c;设计UI 第三步&#xff0c;实现计算逻辑 第四步&#xff0c;测试应用程序 随着移动互联网的普及&#xff0c;手机应用程序已经成为人们生活中不可或缺的一部分。计算器是一类被广泛使用的应用程序之一&#xff0c;因此…

十五、吉布斯采样的理解

由于本人喜欢在纸上手推原理&#xff0c;所以附上照片&#xff0c;欢迎提出建议

MCMC、吉布斯采样

学习视频&#xff1a;B站白板推导 学习和代码教程&#xff1a; Li Hang code 知乎&#xff08;和上面内容一模一样&#xff09; &#xff08;权当参考&#xff09; 关于上面代码中&#xff0c;吉布斯采样二维正态分布的理解&#xff1a; Σ的意思是协方差矩阵&#xff0c;在…

LDA----吉布斯采样

w~Mult(w|p) 这里可以引入一个新的概念:概率图模型,来画出这种模型。如图 3-1所示,图中被涂色的 表示可观测变量,方框表示重复抽取的次数, 表示一篇文档中总共 个单词, 表示M篇文档。也就是说,重复抽取 篇文档,每个文档抽取 个单词,这样的生成模型生成了整个语料(corpus)。 总结…

LDA-模型的实现-----吉布斯采样

https://www.cnblogs.com/nlp-yekai/p/3858705.html?utm_sourcetuicool&utm_mediumreferral 算法 LDA Collapsed Gibbs Sampling 输入&#xff1a;文档集(分词后)&#xff0c;K(主题数)&#xff0c;α&#xff0c;β&#xff0c;iter_number(迭代次数) 输出&#xff1a;…

R语言实现MCMC中的Metropolis–Hastings算法与吉布斯采样

创建测试数据 第一步&#xff0c;我们创建一些测试数据&#xff0c;用来拟合我们的模型。我们假设预测变量和因变量之间存在线性关系&#xff0c;所以我们用线性模型并添加一些噪音。 trueA <- 5trueB <- 0trueSd <- 10sampleSize <- 31# 创建独立的x值x <- (…

马尔科夫过程与吉布斯采样

随机模拟(或者统计模拟)方法有一个很酷的别名是蒙特卡罗方法(Monte Carlo Simulation)。这个方法的发展始于20世纪40年代&#xff0c;和原子弹制造的曼哈顿计划密切相关&#xff0c;当时的几个大牛&#xff0c;包括乌拉姆、冯.诺依曼、费米、费曼、Nicholas Metropolis&#xf…

吉布斯采样的简单描述

几个可以学习gibbs sampling的方法1&#xff0c;读Bishop的Pattern Recognition and Machine Learning&#xff0c;讲的很清楚&#xff0c;但是我记得好像没有例子。2&#xff0c;读artificial Intelligence&#xff0c;2、3版&#xff0c;都有。但是我没读过。3&#xff0c;最…

【ML】线性回归的吉布斯采样(Gibbs Sampling)实现(python)

导航 Bayesian Linear RegressionGibbs SamplingDerving a Gibbs samplerUpdate for β 0 \beta_0 β0​Update for β 1 \beta_1 β1​Update for τ \tau τSynthetic dataGibbs sampler code downlaodReferences Bayesian Linear Regression 考虑只有一个自变量(indepen…

【机器学习】主题建模+隐狄利克雷分配模型(LDA)+吉布斯采样

【主题建模】 大数据时代&#xff0c;面对海量的数据&#xff0c;如果能知道它的主题是什么&#xff0c;从数据压缩的角度来看&#xff0c;我们可以通过很少量的主题来管理很大亮的文档数据集合&#xff0c;从而实现一个比较简洁的操作和管理文档集合的目的&#xff1b;除此之外…

【人工智能】对贝叶斯网络进行吉布斯采样

问题 现要求通过吉布斯采样方法&#xff0c;利用该网络进行概率推理&#xff08;计算 P(RT|SF, WT)、P2(CF|WT)的概率值&#xff09;。 原理 吉布斯采样的核心思想为一维一维地进行采样&#xff0c;采某一个维度的时候固定其他的维度&#xff0c;在本次实验中&#xff0c;假…

matlab bnt工具箱吉布斯采样,吉布斯采样——原理及matlab实现

原文来自:https://victorfang.wordpress.com/2014/04/29/mcmc-the-gibbs-sampler-simple-example-w-matlab-code/ 【注】评论区有同学指出译文理论编码有误,请参考更官方的文献,个人当时仅验证过红色字体部分理论与维基百科中二位随机变量吉布斯采样的结果是否对应,其余部分…

【LDA】吉布斯采样

吉布斯采样是用条件概率得到联合概率分布。 其实是得到我们想要东西的近似解 目录 1 蒙特卡罗2 马尔科夫链3.MCMC采样4 MH采样5 吉布斯采样 1 蒙特卡罗 蒙特卡洛方法是为了解决一些不太好求解的求和或者积分问题。 其实就是一个近似方法&#xff0c;通过采样的多个样本代替原…

机器学习笔记之马尔可夫链蒙特卡洛方法(四)吉布斯采样

机器学习笔记之马尔可夫链蒙特卡洛方法——吉布斯采样 引言回顾&#xff1a;MH采样算法基于马尔可夫链的采样方式细致平衡原则与接收率 MH采样算法的弊端吉布斯采样方法吉布斯采样的采样过程吉布斯采样的推导过程吉布斯采样的代码实现 引言 上一节介绍了将马尔可夫链与蒙特卡洛…

三步完成吉布斯采样Gibbs sampling

吉布斯采样的具体执行过程只需要三个步骤&#xff0c;非常非常简单好理解&#xff0c;其它相关的背景知识能帮助加深理解。 一、Preliminaries Monte Carlo methods 它是很宽泛的一类计算方法&#xff0c;依赖重复的随机采样去获得数值结果。a broad class of computational a…