最近在学习安卓开发,做了个小计算器作为实践。发现网上的计算器教程代码的健壮性不够好,只能够容忍正确的输入。于是我花了几天时间写了个完整的程序。可能是我水平有限,其中条件控制逻辑设计的比较复杂,但我受开源运动影响比较深,我学习了别人的代码,就应该把自己的代码公布出来,即使写的不好,多多少少能为一些人带来一点点帮助吧,同时记录自己的学习历程。

先来展示一下成果:

开发工具我选择了android studio, 诚实的说我对xml并不是那么的了解,所以我只能采用所见即所得的办法,不过这个小项目做下来,感觉比刚开始好多了。

再说一下思路吧,计算器上方是个显示器,是一个TextView,显示器上方的东西是个spinner,作用待会再说,显示器下方都是button,通过监听button的摁下,在TextView上显示用户输入来与用户做交互,然后将TextView上的内容提取出来做运算,再显示再屏幕上。其实大部分的工作都是在做人机交互以及规范用户的输入,真正实现功能的代码并不多。

下面开始贴代码了,先贴xml吧,方便与上面的图片比对

xml代码部分(AndroidMainfest.xml):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:gravity="bottom"android:orientation="vertical"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="9"android:orientation="vertical"><Spinnerandroid:id="@+id/spinner"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="start"android:textSize="50sp" /><TextViewandroid:id="@+id/concle"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="bottom|end"android:maxLines="2"android:minLines="1"android:singleLine="false"android:text="@string/priNum"android:textSize="45sp"/></LinearLayout><TableLayoutandroid:id="@+id/table"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="4"android:gravity="bottom"><TableRowandroid:id="@+id/line1"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"><Buttonandroid:id="@+id/buttonClean"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="@android:color/darker_gray"android:text="@string/button_c"android:textColor="@android:color/holo_red_dark"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonMul"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#fa8e12"android:text="@string/button_mul"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonDiv"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#fa8e12"android:text="@string/button_div"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonDel"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#b22222"android:text="@string/button_del"android:textSize="40sp" /></TableRow><TableRowandroid:id="@+id/line2"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"><Buttonandroid:id="@+id/button7"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_7"android:textSize="40sp" /><Buttonandroid:id="@+id/button8"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_8"android:textSize="40sp" /><Buttonandroid:id="@+id/button9"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_9"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonAdd"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#fa8e12"android:text="@string/button_add"android:textSize="40sp" /></TableRow><TableRowandroid:id="@+id/line3"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"><Buttonandroid:id="@+id/button4"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_4"android:textSize="40sp" /><Buttonandroid:id="@+id/button5"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_5"android:textSize="40sp" /><Buttonandroid:id="@+id/button6"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_6"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonSub"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#fa8e12"android:text="@string/button_sub"android:textSize="40sp" /></TableRow><TableRowandroid:id="@+id/line4"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"><Buttonandroid:id="@+id/button1"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_1"android:textSize="40sp" /><Buttonandroid:id="@+id/button2"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_2"android:textSize="40sp" /><Buttonandroid:id="@+id/button3"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_3"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonList"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:autoText="false"android:background="#FFdab9"android:onClick="showDialog"android:text="@string/button_list"android:textSize="40sp" /></TableRow><TableRowandroid:id="@+id/line5"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"><Buttonandroid:id="@+id/button0"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#cdced1"android:text="@string/button_0"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonPoint"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#ff6347"android:text="@string/button_point"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonCopyright"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#696969"android:text="@string/button_copyright"android:textColor="#800000"android:textSize="40sp" /><Buttonandroid:id="@+id/buttonEqual"style="?android:attr/buttonStyle"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="#fa8e12"android:text="@string/button_equal"android:textSize="40sp" /></TableRow></TableLayout></LinearLayout></android.support.constraint.ConstraintLayout>

代码比较长,我学习xml的时候也挺苦恼的,不过还是耐心的看一下吧,多看几个就没那么陌生了。

接下来是java的代码(MainActivity.java)  注释加在文本的后面:

其中定义了

caculate()          // 实现计算功能的函数

setprecision(String s)        //

showDialog()

showDevDialog()  四个公有方法(不包括监听事件)

package com.era_huang;import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;public class MainActivity extends AppCompatActivity implements View.OnClickListener {// 定义所有按键Button button_0;Button button_1;Button button_2;Button button_3;Button button_4;Button button_5;Button button_6;Button button_7;Button button_8;Button button_9;Button button_point;Button button_add;Button button_sub;Button button_mul;Button button_div;Button button_del;Button button_c;Button button_equal;Button button_list;Button button_copyright;TextView terminal;  // 定义计算器显示屏boolean pointLock1 = false;     // 防止一个数中有多个小数点,摁下一个点后就锁住boolean pointLock2 = false;     // 防止在运算符后连接小数点boolean opraterLock = false;    // 防止两个数之间输入多于两个运算符Spinner spinner;      // 定义了显示屏上那个下拉菜单,用来自动保留小数位数List<String> list;    // spinner中的子选项ArrayAdapter<String> adapter;int reservedDecimalNumber = 4;   // 默认保留的小数位数为4位小数BigDecimal result = BigDecimal.valueOf(0);  // java中的大数值,为了实现精确的计算,因为这是一个计算器@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 让各个button连接对应组件button_0 = findViewById(R.id.button0);button_1 = findViewById(R.id.button1);button_2 = findViewById(R.id.button2);button_3 = findViewById(R.id.button3);button_4 = findViewById(R.id.button4);button_5 = findViewById(R.id.button5);button_6 = findViewById(R.id.button6);button_7 = findViewById(R.id.button7);button_8 = findViewById(R.id.button8);button_9 = findViewById(R.id.button9);button_point = findViewById(R.id.buttonPoint);button_equal = findViewById(R.id.buttonEqual);button_add = findViewById(R.id.buttonAdd);button_sub = findViewById(R.id.buttonSub);button_c = findViewById(R.id.buttonClean);button_mul = findViewById(R.id.buttonMul);button_div = findViewById(R.id.buttonDiv);button_del = findViewById(R.id.buttonDel);button_list = findViewById(R.id.buttonList);button_copyright = findViewById(R.id.buttonCopyright);terminal = findViewById(R.id.concle);// 创建显示屏上的下拉菜单spinner = findViewById(R.id.spinner);list = new ArrayList<>();list.add("4位小数");list.add("0位小数");list.add("1位小数");list.add("2位小数");list.add("6位小数");list.add("8位小数");adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);spinner.setAdapter(adapter);//监听spinnerspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id) {String info = adapter.getItem(position);setprecision(info);}@Overridepublic void onNothingSelected(AdapterView<?> parent) {}});// 监听各个按钮button_0.setOnClickListener(this);button_1.setOnClickListener(this);button_2.setOnClickListener(this);button_3.setOnClickListener(this);button_4.setOnClickListener(this);button_5.setOnClickListener(this);button_6.setOnClickListener(this);button_7.setOnClickListener(this);button_8.setOnClickListener(this);button_9.setOnClickListener(this);button_point.setOnClickListener(this);button_equal.setOnClickListener(this);button_add.setOnClickListener(this);button_sub.setOnClickListener(this);button_c.setOnClickListener(this);button_mul.setOnClickListener(this);button_div.setOnClickListener(this);button_del.setOnClickListener(this);button_list.setOnClickListener(this);button_copyright.setOnClickListener(this);}@Overridepublic void onClick(View v) {// 按键按下阴影动画Animation alphaAnimation = new AlphaAnimation(0.1f, 0);alphaAnimation.setInterpolator(new LinearInterpolator());alphaAnimation.setDuration(100);alphaAnimation.setRepeatCount(1);alphaAnimation.setRepeatMode(Animation.REVERSE);v.startAnimation(alphaAnimation);// 获取显示器上的字符串String str = terminal.getText().toString();//判断那个键被按下switch (v.getId()) {// 数值类按键case R.id.button0:case R.id.button1:case R.id.button2:case R.id.button3:case R.id.button4:case R.id.button5:case R.id.button6:case R.id.button7:case R.id.button8:case R.id.button9://如果显示器上显示错误,摁下任意数字键归零if (str.equals("错误"))terminal.setText("0");//当有数字被按下,就不存在运算符连接point(小数点)的情况,锁2打开pointLock2 = false;opraterLock = false;String text1;// 显示屏默认为0,如果为0显示button对应的值,// 如果不为0,显示屏上的字符串与摁下的字符串连接if (str.equals("0")) {text1 = "" + ((Button) v).getText();} else {text1 = str + ((Button) v).getText();}terminal.setText(text1);break;//小数点摁键,如果两个锁都打开,就可以摁下小数点case R.id.buttonPoint:if (!pointLock1 && !pointLock2) {String text2 = str + ((Button) v).getText();terminal.setText(text2);pointLock1 = true;}break;// 运算符按键,如果摁下,运算符后的为另一个数字,则可以打下一个小数点//所以锁1打开。而运算符后不能接小数点,所以锁2锁上,等打数字后,锁2解开case R.id.buttonAdd:case R.id.buttonSub:case R.id.buttonMul:case R.id.buttonDiv://如果前一位不为小数点才能摁下运算符按键if (str.charAt(str.length() - 1) != '.' && !opraterLock) {pointLock1 = false;pointLock2 = true;opraterLock = true;String text3 = str + ((Button) v).getText();terminal.setText(text3);}break;//删除键case R.id.buttonDel://当小数点被删除后,锁1要打开,不然无法再次输入小数点,// 因为锁1只有在摁下运算符后才会打开if (str.charAt(str.length() - 1) == '.') {pointLock1 = false;pointLock2 = false;}//如果运算符被删掉,opraterLock打开,能够再次输入运算符//pointLock1要锁上,以免在输入运算符再将其删除后,输入一个数字即又可以输入point的情况if (str.charAt(str.length() - 1) == '+' || str.charAt(str.length() - 1) == '-' ||str.charAt(str.length() - 1) == '*' || str.charAt(str.length() - 1) == '/') {opraterLock = false;pointLock1 = true;}//如果长度大于一,返回去掉最后一个字符的字符串if (str.length() > 1) {str = str.substring(0, str.length() - 1);}//否则(即长度为1时直接设置显示器中为0)else {str = "0";}terminal.setText(str);break;//清屏操作所有锁都打开case R.id.buttonClean:str = "0";terminal.setText(str);pointLock1 = false;pointLock2 = false;opraterLock = false;break;//求运算结果case R.id.buttonEqual:char lastChar = str.charAt(str.length() - 1);if (lastChar != '.' && lastChar != '+' && lastChar != '-'&& lastChar != '*' && lastChar != '/') {try {caculate();} catch (Exception e) {str = "错误";terminal.setText(str);}}break;case R.id.buttonList:showDialog();break;case R.id.buttonCopyright:showDevDialog();break;}}public void caculate() {String expression = terminal.getText().toString();// 利用正则表达式将各个数值分开,提取到数组里String[] expArr = expression.split("\\+|\\-|\\*|\\/");String[] operate = expression.split("\\d+|\\.");String[] foperate = new String[100];double[] numArr = new double[expArr.length];int index = 0, index1;double sum = 0;if (expression.charAt(0) == '-') {index1 = 1;} else {index1 = 0;}for (; index1 < expArr.length; index1++) {numArr[index1] = Double.parseDouble(expArr[index1]);}for (String mystr : operate) {if ((!mystr.equals("")) && (!mystr.equals(null))) {foperate[index] = mystr;}index++;}index = 0;for (String operater : foperate) {if (operater != null) {if (operater.equals("-")) {numArr[index + 1] = -numArr[index + 1];}index++;}}index = 0;for (int i = 0; i < foperate.length; i++) {if (foperate[i] != null) {if (foperate[i].equals("*")) {numArr[index + 1] = numArr[index] * numArr[index + 1];numArr[index] = 0;foperate[i] = null;} else if (foperate[i].equals("/")) {numArr[index + 1] = numArr[index] / numArr[index + 1];numArr[index] = 0;foperate[i] = null;}index++;}}for (Double d : numArr) {sum += d;}BigDecimal accurateSum = BigDecimal.valueOf(sum).setScale(reservedDecimalNumber, BigDecimal.ROUND_HALF_UP);result = accurateSum;terminal.setText(String.valueOf(accurateSum));}public void setprecision(String s) {String formatS = s.substring(0, 1);reservedDecimalNumber = Integer.valueOf(formatS);if (!result.equals(BigDecimal.valueOf(0))) {terminal.setText(String.valueOf(result.setScale(reservedDecimalNumber, BigDecimal.ROUND_HALF_UP)));}}// 消息提示框public void showDialog() {new AlertDialog.Builder(this).setMessage("计算值记录功能将在下次重大改良中开发,感谢大家支持!").setPositiveButton("确定", null).show();}// 消息提示框public void showDevDialog() {new AlertDialog.Builder(this).setMessage("开发者:Era_Huang\nQQ:1295289600\n倾尽所能为用户开发最优质的应用").setPositiveButton("确定", null).show();}
}

加注释真的加的心累,附上apk的度盘:

https://pan.baidu.com/s/1A1BwwzTvC6OCcrbpCap_lA

希望能和大家一起进步

android计算器开源小项目代码(附安装包.apk)相关推荐

  1. 【ArcGIS微课1000例】0065:ArcGISEarth移动端Android下载安装与使用(附安装包)

    ArcGIS Earth移动版为不同用户人群,提供专业友好的三维交互体验.本文讲解ArcGIS Earth移动端(Android版本)下载.安装与使用(附ArcGIS Earth移动端安装包). 文章 ...

  2. 知云文献翻译打不开_论文翻译小工具,一键即可免费翻译全文| 知云文献翻译、彩云小译(附安装包)...

    Ⅰ 最近正在秃头写论文,需要可以自动一键全文翻译的工具,一番询问和测试之后,强烈推荐知云文献和彩云小译. 知云文献翻译是一个软件,使用时,只需要将需要翻译的文件拉入软件页面,点击需要翻译的内容,即可以 ...

  3. 暑期Android游戏开发——小兔子跳铃铛(附源码)

    暑期Android游戏开发--小兔子跳铃铛(附源码) 一. 背景说明 我在南京的一所高校学习软件工程.学院里每年会举行一次"创新杯"软件比赛,鼓励同学自主学习和创新.我和几个好兄弟 ...

  4. 分享一个我开发的MVVM架构的开源小项目

    本文同步发表于我的微信公众号,扫一扫文章底部的二维码或在微信搜索 郭霖 即可关注,每个工作日都有文章更新. 大家好,今天跟大家分享一个我开发的MVVM架构的开源小项目. 话说这个小项目已经提前跟大家预 ...

  5. 我的MVVM 开源小项目已发布~

    前言 前几篇文章中,我们学习了许多Jetpack架构组件,虽说每个架构组件都是相互协调使用的,但是相信还是有很多人不知道如何搭建一个Jetpack的项目,不知道网络请求该放在什么地方,或者说其他的开源 ...

  6. 可以运行的electron开源小项目

    可以运行的electron开源小项目 文章目录 可以运行的electron开源小项目 1. vue-electron-notes笔记软件 安装依赖 本地启动项目 构建安装包 2 Electron AP ...

  7. qt小项目 代码实现简易的QQ聊天界面

    qt小项目 代码实现简易的QQ聊天界面 代码 效果图 总结 代码 myDialog.h #ifndef MAINWINDOW_H #define MAINWINDOW_H#include <QW ...

  8. Git简介、安装教程附安装包

    文章目录 前言 一.git简介 二.下载安装教程 前言 团队合作,使用git是必不可少的,下面是git相关内容以及安装教程附安装包 一.git简介 1) 版本库(version control sys ...

  9. Android安装包APK如何解压

    参考:http://hellorheaven.iteye.com/blog/1012932 今天遇到一种情况,我们提供给客户的安装包APK是56.3M,客户觉得很大,通过看代码发现模型20.3M + ...

最新文章

  1. 前后端分离的探索(二)
  2. hdu 5273 Dylans loves sequence 逆序数简单递推
  3. 直接插入排序算法实现思想个人理解
  4. 【物联网智能网关-15】WAV播放器(WinForm+WavPlay库实例)
  5. [转载]MongoDB开发学习 经典入门
  6. python人工智能-Python和人工智能的关系,看完你就明白了!
  7. pod中mysql配置文件修改_通过configmap更新k8s里的mysql配置文件
  8. java基础将一个int数组转换成一个字符串
  9. 4012最长的最短路径的求解(C++,迪杰斯特拉算法,注释全,附迪杰斯特拉算法详解文章)
  10. Mysql-Windows下重置密码/修改密码
  11. 牛逼!用 MySQL 实现一个分布式锁,这也太强了。。。
  12. 机器学习第五回——学习方法与学习曲线
  13. 博客制作系 -- 2.4. Git
  14. 风险预测模型_利用好预后预测模型,2个月发篇4分+SCI不是梦
  15. NetFlow网络流量分析
  16. 金山词霸笔试题目笔记
  17. f2fs系列之一:实战f2fs 下载、编译和挂载 [转载系列]
  18. 基于STM32+华为云IOT设计的云平台监控系统
  19. Rust更适合经验较少的程序员?
  20. python解法:【PAT520砖石争霸赛】7-2真的恭喜你(10)

热门文章

  1. LVS 引入keepalived自动切换机制
  2. #小何不断努力# Day1
  3. 《0Day安全》之堆溢出
  4. linux 负载均衡技术之 LVS
  5. 第三届厦门国际银行数创金融杯金融营销建模大赛-BaseLine
  6. 阿里云 mysql 修改root密码修改_设置及修改MySQL root用户密码 - MySQL中文参考手册...
  7. 2016..8.25 切题总结
  8. 阿里云天池携手产学研心血管专家,共话心血管AI发展
  9. Java8中字符串连接(join)收集器 Collectors.joining
  10. Python基础——修改Python字典中的key(键)