最近在学习安卓开发,做了个小计算器作为实践。发现网上的计算器教程代码的健壮性不够好,只能够容忍正确的输入。于是我花了几天时间写了个完整的程序。可能是我水平有限,其中条件控制逻辑设计的比较复杂,但我受开源运动影响比较深,我学习了别人的代码,就应该把自己的代码公布出来,即使写的不好,多多少少能为一些人带来一点点帮助吧,同时记录自己的学习历程。
先来展示一下成果:
开发工具我选择了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">
<LinearLayout
android: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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="9"
android:orientation="vertical">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="start"
android:textSize="50sp" />
<TextView
android: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>
<TableLayout
android:id="@+id/table"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="4"
android:gravity="bottom">
<TableRow
android:id="@+id/line1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android: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" />
<Button
android: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" />
<Button
android: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" />
<Button
android: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>
<TableRow
android:id="@+id/line2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android: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" />
<Button
android: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" />
<Button
android: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" />
<Button
android: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>
<TableRow
android:id="@+id/line3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android: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" />
<Button
android: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" />
<Button
android: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" />
<Button
android: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>
<TableRow
android:id="@+id/line4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android: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" />
<Button
android: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" />
<Button
android: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" />
<Button
android: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>
<TableRow
android:id="@+id/line5"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android: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" />
<Button
android: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" />
<Button
android: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" />
<Button
android: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中的大数值,为了实现精确的计算,因为这是一个计算器
@Override
protected 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);
//监听spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String info = adapter.getItem(position);
setprecision(info);
}
@Override
public 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);
}
@Override
public 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
希望能和大家一起进步