The Android calculator you want, it’s coming today!
This project mainly realizes the simple calculator function, including the basic operation of addition, subtraction, multiplication and division, as well as the decimal point and zero clearing function. It can be regarded as a good Android interface and button click event learning example. Students who have just used the simulator to show Hello world or students who have never touched Android can start directly.
The Android version has been adjusted earlier. Now it is 4.2.1. Of course, the version does not affect the code syntax, but the gradle is changed. Just change the gradle path when importing my project. If you encounter problems, you can refer to these two experiences: quickly solve the problem of gradle error reporting of Android projects, and how to import Android projects with different gradle versions
Before talking about layout, let's introduce GridLayout and its advantages:
Let's look at the layout code of the calculator:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
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"
android:orientation="vertical">
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top">
<!--输入的文本框-->
<EditText
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="请输入数字"
android:textSize="30dp"/>
</GridLayout>
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="5"
android:columnCount="4"
android:layout_gravity="center|top">
<Button
android:id="@+id/btn1"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:layout_columnSpan="1"
android:text="1" />
<Button
android:id="@+id/btn2"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="2" />
<Button
android:id="@+id/btn3"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="3" />
<Button
android:id="@+id/divide"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="/" />
<Button
android:id="@+id/btn4"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="4" />
<Button
android:id="@+id/btn5"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="5" />
<Button
android:id="@+id/btn6"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="6" />
<Button
android:id="@+id/multi"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="*" />
<Button
android:id="@+id/btn7"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="7"
/>
<Button
android:id="@+id/btn8"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="8" />
<Button
android:id="@+id/btn9"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="9" />
<Button
android:id="@+id/sub"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="—" />
<Button
android:id="@+id/btn0"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="0" />
<Button
android:id="@+id/point"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:layout_columnSpan="1"
android:text="." />
<Button
android:id="@+id/clean"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="del" />
<Button
android:id="@+id/plus"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_margin="5dp"
android:layout_rowSpan="1"
android:text="+" />
<Button
android:id="@+id/equ"
android:layout_width="390dp"
android:layout_height="60dp"
android:layout_columnSpan="4"
android:layout_margin="5dp"
android:text="="
android:textSize="30dp"/>
</GridLayout>
</GridLayout>
The code is very simple. Each button has an ID set. The "=" button spans one line, and others are added directly. By default, each component occupies one line and one column. Another thing to note: we use Android: layout_ Rowspan and Android: Layout_ Columnspan sets whether the component spans multiple rows or columns; If you want the component to fill the crossed rows or columns, you need to add the following attribute: Android: layout_ gravity = “fill”。 Just like the part of the calculator that displays numbers (result input box). Let's take a look at the interface Preview:
Many buttons are defined, representing 0-9, addition, subtraction, multiplication and division, decimal point, equal to and zero clearing respectively. Here, the variable name must be concise and easy to understand. Do not define the variable name at will and form a good habit.
//运算符
private Button plus;//加号+
private Button sub;//减号-
private Button multi; //乘号*
private Button divide;// 除号/
private Button point; //小数点.
private Button equ; //等于=
private Button clean;//清除输入框
Bind the variable just defined with the set control through ID, so that the whole variable represents the control. Remember, when writing Android, you must write layout first, and then write the main function.
plus = findViewById(R.id.plus);// +
sub = findViewById(R.id.sub);// -
multi = findViewById(R.id.multi);// *
divide = findViewById(R.id.divide); // /
point = findViewById(R.id.point);//小数点
equ = findViewById(R.id.equ);//=
clean = findViewById(R.id.clean);//清空
Add a click event to each control, which is the most commonly used method. The system listens to your action and gives a response.
plus.setOnClickListener(this);
sub.setOnClickListener(this);
multi.setOnClickListener(this);
divide.setOnClickListener(this);
equ.setOnClickListener(this);
point.setOnClickListener(this);
clean.setOnClickListener(this);
Here we use the variable clear_ Flag to judge, it is the empty flag, true is empty, false is not empty. Then classify numbers, operators and other operations.
public void onClick(View view) {
//获取文本内容
String input = editText.getText().toString();
switch (view.getId()){//选择按钮id
case R.id.btn0:
case R.id.btn1:
case R.id.btn2:
case R.id.btn3:
case R.id.btn4:
case R.id.btn5:
case R.id.btn6:
case R.id.btn7:
case R.id.btn8:
case R.id.btn9:
case R.id.point:
if(clear_flag){
clear_flag = false;
editText.setText("");//赋值为空
}
editText.setText(input + ((Button)view).getText());//结果集就为本身
break;
case R.id.plus:
case R.id.sub:
case R.id.multi:
case R.id.divide://加减乘除一起
if(clear_flag){
clear_flag = false;
input = "";
editText.setText("");
}
editText.setText(input + " " + ((Button)view).getText() + " ");
break;
case R.id.clean://清除输入框
if(clear_flag){
clear_flag = false;
input = "";
editText.setText("");
}else if(input != null || !input.equals("")) {//如果获取到的内容为空
editText.setText(input.substring(0, input.length() - 1));//结果集为空
}
break;
case R.id.equ://运算结果等于
getResult();//调用处理结果集的方法
break;
}
}
This part of the method is to calculate the results of two numerical operations, that is, if else statements. Equals () is the comparison of two objects. If they are the same, it is true, otherwise it is false, and contains () is the inclusion relationship, including true, otherwise it is false.
//运算结果的方法
private void getResult(){
String exp = editText.getText().toString();//获取文本框的内容
if(exp==null||exp.equals("")){
return;
}
if(!exp.contains(" ")){
return;
}
if(clear_flag){
clear_flag = false;
return;
}
clear_flag = true;
double result = 0;
//进行截取
//运算符前的数字
String s1 = exp.substring(0,exp.indexOf(" "));
//运算符
String op = exp.substring(exp.indexOf(" ")+1,exp.indexOf(" ")+2);
//运算符后的数字
String s2 = exp.substring(exp.indexOf(" ")+3);
if(!s1.equals("")&&!s2.equals("")) {//如果包含小数点的运算
double d1 = Double.parseDouble(s1);//则数字都是double类型
double d2 = Double.parseDouble(s2);
if (op.equals("+")) {//如果是 +
result = d1 + d2;
} else if (op.equals("-")) {
result = d1 - d2;
} else if (op.equals("*")) {
result = d1 * d2;
} else if (op.equals("/")) {
if (d2 == 0) { //如果被除数是0
result = 0; //则结果是0
}
else {//否则执行正常是除法运算
result = d1 / d2;
}
}
if (!s1.contains(".") && !s2.contains(".") && !op.equals("/")) {//如果是整数类型
int r = (int) result; //都是整形
editText.setText(r + "");
} else{
editText.setText(result + "");
}
}else if(!s1.equals("") && s2.equals("")){//如果是只输入运算符前的数
editText.setText(exp);//直接返回当前文本框的内容
}else if(s1.equals("") && !s2.equals("")){//如果是只输入运算符后面的数
double d2 = Double.parseDouble(s2);
//运算符前没有输入数字
if (op.equals("+")) {
result = 0 + d2;
} else if (op.equals("-")) {
result = 0 - d2;
} else if (op.equals("*")) {
result = 0;
} else if (op.equals("/")) {
result = 0;
}
if (!s1.contains(".") && !s2.contains(".")) {
int r = (int) result;
editText.setText(r + "");
} else{
editText.setText(result + "");
}
}else {
editText.setText("");
}
}
1. Turn on the simulator to run and enter two numbers
This project is an example of basic test layout and controls. It is a very good example for beginners. It can be used as the second example after Hello world. After carefully digesting the contents, it will be very fast in the future.
Students who need source learning can pay attention to my WeChat official account: old whale's underground castle, reply: calculator, you can get source code, and more free Android projects, etc. I'd like to give you a carefully sorted Android learning classic: Android project and Android tutorial summary (epic classic)