1.简介
运用Android Studio编写一个简单计算器APP。界面如下:
2.主要原理
通过对按钮进行监听,获取相应按钮的值,并根据不同的按钮做出不同响应。(设当前显示的值为result)
- 数字按钮
0 :判断result是否为0,是 —— 不作反应
否 —— 拼接在result后面
1-9:拼接在result后面
- 功能按钮
“.”:根据result的结构判断是否能够使用,能 —— 进行拼接
不能 —— 不作反应
“+ - * /”:点击时,判断是否能进行运算。如:result为3时,点击+,直接进行拼接,即result为"3+"
result为3+2时,点击+,作出运算,置result为"5+"
“=”:点击时,根据result的结构判断能否进行运算,能 —— 进行运算
不能 —— 不作反应
“清除”:点击时,置result的值为0
3.运行截图
运算3+6,由于转换成Double型,故得出结果9.0
上式得出的结果9.0,加上3,再按“*”,会先得到前半部分的结果,再继续进行运算。
最后按“=”,得出最终结果。
4.源代码
//activity_main.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">
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="6"
android:columnCount="4"
android:layout_marginHorizontal="15dp">
<TextView
android:id="@+id/showRst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:layout_marginLeft="4px"
android:gravity="left"
android:text="0"