Android 简单计算机的实现
新建工程
首先是创建一个新的工程
新建步骤如下:
点击next后
点击Next
选择Empty Activity选项
将第一个默认勾选的选项取消勾选,此选项是创建一个默认layout文件,因为我们要使用自己的layout文件作为布局文件,所以我们把此选项改为不勾选,最后点击finish完成创建。
新建文件错误解决
新建完成后文件报错,报错原因是build.grade文件中的版本不符所造成的问题,进行如下修改:
打开build.grade的文件:
将其中的版本号30改为26
如上图所示,修改完成后点击Try again重新加载,错误即可解决。
代码实现
我们要实现代码首先需要一个写代码的文件,首先创建一个布局代码的容器即在res文件夹下新建一个directory文件并将其命名为layout
接着在layout文件夹下新建一个布局文档(Layout resource file)用于存放布局代码,示例:将文件名命名为main
布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textResult" //命名id是为后面计算器功能的实现做准备
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:gravity="right" //设置文本对齐方式为左对齐
android:text="" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> //表示该布局水平对齐
<Button //按钮
android:id="@+id/btnCLs" //为设置监听做准备
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" //android:layout_weight用于给一个线性布局中的诸多视图的重要度赋值
android:text="C"/>
<Button
android:id="@+id/btnDel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Del"/>
<Button
android:id="@+id/btnChu"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="÷"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btnOne"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1"/>
<Button
android:id="@+id/btnTwo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2"/>
<Button
android:id="@+id/btnThree"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3"/>
<Button
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="+"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btnFour"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="