目的
根据书本例题的计算器界面,开发一个简单的计算器,并实现功能。
工具及环境
使用java语言,在Android studio平台上进行开发
功能设计
实现加减乘除的运算功能和清屏的功能
设计思路
首先设计一个可视化的界面,供用户输入数据并查看结果。
用户通过点击相应按钮输入正确的表达式,计算器进行相应的加减乘除运算,且可以进行小数和整数的运算
代码
selector_orange_bg.xml(点击按钮会有灰色阴影效果)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/shape_rectangle_orange_grey"/>
<item android:drawable="@drawable/shape_rectangle_orange"/>
</selector>
selector_white_bg.xml (点击按钮会有灰色阴影效果)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/shape_rectangle_white_grey"/>
<item android:drawable="@drawable/shape_rectangle_white"/>
</selector>
shape_rectangle_orange.xml (运算符功能键的背景颜色设置)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#e47126"/>
<stroke
android:width="1dp"
android:color="#333333"/>
</shape>
shape_rectangle_orange_grey.xml (点击按钮之后的灰色阴影设置)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#b55f1c"/>
<stroke
android:width="1dp"
android:color="#333333"/>
</shape>
shape_rectangle_white.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ffffff"/>
<stroke
android:width="1dp"
android:color="#333333"/>
</shape>
shape_rectangle_white_grey.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#999999"/>
<stroke
android:width="1dp"
android:color="#333333"/>
</shape>
activity_main.xml(UI设计)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/result"
android:textColor="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="65sp"
android:enabled="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height