Android开发:基于Kotlin编写一个简易计算器

这篇具有很好参考价值的文章主要介绍了Android开发:基于Kotlin编写一个简易计算器。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

本着程序员“拥抱变化”的思想,最近开始学Kotlin了。感觉还是得通过实战来入门一门新语言,所以打算写一个基于Kotlin语言的计算器,本文对开发过程以及学习Kotlin的一些知识进行了记录。
计算器的全部源码已经放到了我的Github中,需要的伙伴自取:Calculator

Kotlin学习tips

  1. Kotlin中文站:https://www.kotlincn.net/
    这是Kotlin的官方中文网站,里面有Kotlin的介绍、入门使用以及Kotlin官方文档中文版等;
  2. Android开发者平台内对Kotlin编程的介绍页面:https://developer.android.google.cn/kotlin/first
    Kotlin目前已经是Android官方推荐的编程语言,因此在Android开发者平台也有对使用Kotlin进行Android编程的方法介绍以及使用入门等。

界面绘制及控件绑定

UI界面绘制

使用TextView控件进行输入以及结果展示,使用Button控件充当按键。由于时间限制,这里直接使用LinearLayout布局进行实现,缺点是布局层级嵌套太多,总共嵌套了三层LinearLayout,有空的小伙伴们可以自行优化一下。布局文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Hello World!"
        android:textAllCaps="false"
        android:textSize="30sp"
        android:gravity="right|bottom"
        android:background="@drawable/bg_frame"
        android:padding="15dp"
        android:id="@+id/mtv_result"
        />

    <LinearLayout
        android:layout_weight="3"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_marginTop="15dp"
        android:background="@drawable/bg_frame"
        android:orientation="vertical">

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:padding="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="+"
                android:id="@+id/btn_add"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="-"
                android:id="@+id/btn_subtract"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="*"
                android:id="@+id/btn_multiply"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="/"
                android:id="@+id/btn_divide"/>
        </LinearLayout>

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="1"
                android:id="@+id/btn_one"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="2"
                android:id="@+id/btn_two"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="3"
                android:id="@+id/btn_three"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="0"
                android:id="@+id/btn_zero"/>
        </LinearLayout>

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="4"
                android:id="@+id/btn_four"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="5"
                android:id="@+id/btn_five"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="6"
                android:id="@+id/btn_six"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="C"
                android:id="@+id/btn_clean"/>

        </LinearLayout>

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="7"
                android:id="@+id/btn_seven"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="8"
                android:id="@+id/btn_eight"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="9"
                android:id="@+id/btn_nine"/>

            <Button
                android:textSize="28sp"
                android:layout_margin="5dp"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/bg_frame"
                android:text="="
                android:id="@+id/btn_calculate"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

控件绑定

MainActivity内,首先对UI控件进行绑定。我们单独写一个init()方法,并在onCreate()里进行调用,init()方法代码如下:

/**
 * 对控件进行初始化
 * */
fun init() {
    mTvResult = findViewById(R.id.mtv_result)
    mBtnAdd = findViewById(R.id.btn_add)
    mBtnSubtract = findViewById(R.id.btn_subtract)
    mBtnMultiply = findViewById(R.id.btn_multiply)
    mBtnDivide = findViewById(R.id.btn_divide)
    mBtnCalculate = findViewById(R.id.btn_calculate)
    mBtnOne = findViewById(R.id.btn_one)
    mBtnTwo = findViewById(R.id.btn_two)
    mBtnThree = findViewById(R.id.btn_three)
    mBtnFour = findViewById(R.id.btn_four)
    mBtnFive = findViewById(R.id.btn_five)
    mBtnSix = findViewById(R.id.btn_six)
    mBtnSeven = findViewById(R.id.btn_seven)
    mBtnEight = findViewById(R.id.btn_eight)
    mBtnNine = findViewById(R.id.btn_nine)
    mBtnZero = findViewById(R.id.btn_zero)
    mBtnCln = findViewById(R.id.btn_clean)
}

Button点击事件

为了使代码简洁,我们使MainActivity实现View.OnClickListener接口并重写onClick()方法,在该方法内对每个Button的点击事件进行编程,代码如下:

/**
 * 点击事件的具体代码
 * */
override fun onClick(p0: View?) {
    Log.d("baowenbei", "click")
    when (p0?.id) {
        R.id.btn_zero -> addNum(0)
        R.id.btn_one -> addNum(1)
        R.id.btn_two -> addNum(2)
        R.id.btn_three -> addNum(3)
        R.id.btn_four -> addNum(4)
        R.id.btn_five -> addNum(5)
        R.id.btn_six -> addNum(6)
        R.id.btn_seven -> addNum(7)
        R.id.btn_eight -> addNum(8)
        R.id.btn_nine -> addNum(9)
        R.id.btn_calculate -> equal()
        R.id.btn_add -> addOperate('+')
        R.id.btn_subtract -> addOperate('-')
        R.id.btn_multiply -> addOperate('*')
        R.id.btn_divide -> addOperate('/')
        R.id.btn_clean -> cln()
    }
}

需要注意的是,Kotlin并不支持switch语句,但Kotlin的when关键字能够起到类似功能。
之后,我们给每个Button设置点击事件监听,为了代码美观,我们仍封装到单独的方法里,代码如下:

/**
 1. 设置点击事件
 2. */
fun setClickEvent() {
    mBtnCalculate.setOnClickListener(this)
    mBtnAdd.setOnClickListener(this)
    mBtnMultiply.setOnClickListener(this)
    mBtnSubtract.setOnClickListener(this)
    mBtnDivide.setOnClickListener(this)
    mBtnOne.setOnClickListener(this)
    mBtnTwo.setOnClickListener(this)
    mBtnThree.setOnClickListener(this)
    mBtnFour.setOnClickListener(this)
    mBtnFive.setOnClickListener(this)
    mBtnSix.setOnClickListener(this)
    mBtnSeven.setOnClickListener(this)
    mBtnEight.setOnClickListener(this)
    mBtnNine.setOnClickListener(this)
    mBtnZero.setOnClickListener(this)
    mBtnCln.setOnClickListener(this)
}

运算逻辑

整体逻辑

本计算器可以将按键分为数字、运算符、“=”、“clean”四个类型,根据四个类型分别编写对应的代码逻辑;同时,需要编写一个show()方法进行输入展示。我们新建一个mixList用于存储已经输入的运算符及数字。最后,在onCreate()方法里进行调用。

边界情况

首先需要考虑输入的合法性:

  1. 运算符合法性问题。包括表达式第1位必须是数字、不能连续输入多个运算符、表达式不能以运算符结尾等。我们通过设置两个变量numCountoperateCount分别表示已输入的数字个数以及运算符个数,并确保operateCount < numCount来保证运算符合法性。
  2. 运算符优先级问题。不同的运算符具有不同的优先级。在本文提出的计算器中,只实现了加减乘除4个功能,因此优先级可以分为两步,即“先乘除、再加减”。我通过两个for循环实现。
  3. 除0问题。这也需要进行特殊判断。

输入展示

我们使用一个StringBuilder变量对mixList里的所有元素进行拼接,并进行显示,代码如下:

/**
 * 构建表达式的String形式并展示
 * */
fun show(list: ArrayList<String>) {
    if (list.size == 0) mTvResult.setText("0")
    var sb = StringBuilder()
    for (item in list) {
        sb.append(item)
    }
    mTvResult.setText(sb)
}

点击数字键

点击数字键,需要将情况区分为当前输入的是1位数字还是已经输入了多位数字两种情况,具体代码如下:

/**
 * 点击数字时调用此函数
 * */
fun addNum(num: Long) {
    if (operateCount == numCount) {
        // 当前为1位的数字
        numCount++
        mixList.add(num.toString())
    } else {
        // 当前为多位的数字
        val numPlus: Long = mixList.get(mixList.size - 1).toLong() * 10 + num
        mixList.set(mixList.size - 1, numPlus.toString())
    }
    // 实时展示界面变化
    show(mixList)
}

点击运算符键

点击运算符键,需要对运算符的输入合法性进行判断,具体代码如下:

/**
 * 点击运算符时调用此函数
 * */
fun addOperate(operate: Char) {
    if (numCount == 0) return
    if (operateCount < numCount) {
        operateCount++
        mixList.add(operate.toString())
    } else if (operateCount == numCount) {
        mixList.set(mixList.size - 1, operate.toString())
    }
    show(mixList)
}

点击“=”

点击“=”,即需要进行输入判断,具体代码如下:

/**
 * 点击“=”后调用此函数
 * */
fun equal() {
    // 当前只输入数字,不需要计算,直接返回
    if (operateCount == 0) return
    // 当前最后一位为运算符,不合法,对最后一位运算符进行删除
    if (operateCount == numCount) {
        mixList.removeAt(mixList.size - 1)
    }
    // 计算表达式的值
    calculate()
    // 进行界面展示
    show(mixList)
}

其中,calculate()为表达式计算方法,需要根据运算符优先级进行编程实现,具体代码如下:

/**
 * 具体的计算函数
 * */
fun calculate() {
    // 优先进行乘除运算
    for (i in mixList.indices) {
        // 兜底判断,防止后续的删除操作导致List长度减小,导致下标溢出
        if (i > mixList.size - 1) break;
        if (mixList.get(i).equals("*")) {
            // 计算“乘”
            val tmp: Long = mixList.get(i - 1).toLong() * mixList.get(i + 1).toLong()
            // 更新值并删除相关操作数
            mixList.set(i - 1, tmp.toString())
            mixList.removeAt(i)
            mixList.removeAt(i)
        } else if (mixList.get(i).equals("/")) {
            // 对非法输入“除0”进行判断
            if (mixList.get(i + 1).equals("0")) break;
            val tmp: Long = mixList.get(i - 1).toLong() / mixList.get(i + 1).toLong()
            mixList.set(i - 1, tmp.toString())
            mixList.removeAt(i)
            mixList.removeAt(i)
        }
    }

    // 进行加减运算
    for(i in mixList.indices) {
        // 兜底判断,防止后续的删除操作导致List长度减小,导致下标溢出
        if (i > mixList.size - 1) break;
        if (mixList.get(i).equals("+")) {
            val tmp: Long = mixList.get(i - 1).toLong() + mixList.get(i + 1).toLong()
            mixList.set(i - 1, tmp.toString())
            mixList.removeAt(i)
            mixList.removeAt(i)
        } else if (mixList.get(i).equals("-")) {
            val tmp: Long = mixList.get(i - 1).toLong() - mixList.get(i + 1).toLong()
            mixList.set(i - 1, tmp.toString())
            mixList.removeAt(i)
            mixList.removeAt(i)
        }
    }
}

点击“clean”键

点击“clean”键,即对程序进行重置,具体代码如下:

/**
 * 重置操作
 * */
fun cln() {
    operateCount = 0
    numCount = 0
    mixList.clear()
    mTvResult.setText("0")
}

在onCreate()方法里调用

所有子方法编写完成后,我们在onCreate()方法里调用init()方法以及为Button设置监听事件,具体代码如下:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    // 进行控件绑定
    init()
    // 设置点击事件
    setClickEvent()
    // 首次进入,重置一次程序
    cln()
}

成果展示

Android开发:基于Kotlin编写一个简易计算器文章来源地址https://www.toymoban.com/news/detail-426478.html

后记

  1. 本文的运算逻辑部分参考了博文:https://blog.csdn.net/m0_46651408/article/details/117030022,并对它的一些边界情况进行了修改;
  2. 由于时间有限,这个计算器只实现了加减乘除4个功能,也没有添加退格等功能,感兴趣的小伙伴可以自行完善;
  3. 最后贴一下个人公众号:Android开发二三事 ,平时会发一些编程相关的推文,二维码如下,欢迎关注~
    Android开发:基于Kotlin编写一个简易计算器

到了这里,关于Android开发:基于Kotlin编写一个简易计算器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Android Studio简易计算器

    目录 第一步,创建新项目 第二步,设计UI 第三步,实现计算逻辑 第四步,测试应用程序 随着移动互联网的普及,手机应用程序已经成为人们生活中不可或缺的一部分。计算器是一类被广泛使用的应用程序之一,因此学习如何开发一款简易的计算器应用程序是学习Android Stu

    2024年02月08日
    浏览(24)
  • Qt 制作一个简易的计算器

    1.通过UI界面封装出计算器的大致模型 进入设计页面后,左侧会有各种控件,可以将他们拖拽到你想编辑的窗口中,我们要做的是计算器,所以只用到很少几个控件,我们最主要用到Push Button这个控件来做我们计算器的按钮,lineEdit显示数字,我们可以将它拖拽到窗口,然后就

    2024年02月05日
    浏览(104)
  • 用python制作一个简易计算器

    这是一个用Python制作简单计算器的教程。你可以根据需要进行更多的改进,例如添加其他运算符或功能。 首先,我们需要创建一个简单的用户界面,用于显示计算器的按键和结果。在Python中,我们可以使用 tkinter 库来创建图形用户界面。创建一个新的Python文件,并将其命名为

    2024年02月11日
    浏览(34)
  • 制作一个简易的计算器app

    github项目地址:https://github.com/13008451162/AndroidMoblieCalculator 笔者的Ui制作的制作的比较麻烦仅供参考,在这里使用了多个LinearLayout对屏幕进行了划分。不建议大家这样做最好使用GridLayout会更加快捷简单 笔者大致划分是这样的: 使用了四个大框,在第四个大框里面有多个小框

    2024年02月15日
    浏览(33)
  • 【Android】控件与布局入门 - 简易计算器

    目录 1. 基础开发环境 2. 计算器的布局和相关按钮 3. 计算器的主要运算逻辑 4. APK 文件 5. 项目源码 JDK:JDK17 Android Studio:Android Studio Giraffe | 2022.3.1 Android SDK:Android API 34 Gradle: gradle-8.0-bin.zip 使用 LinearLayout 和 GridLayout 实现计算器的交互前端。 layout 文件如下 相关 values 如下:

    2024年02月14日
    浏览(35)
  • JavaScript 用三种方法做一个简易计算器

    基本数据类型 / 使用对象创建 new执行过程 // 1.new构造函可以在内存中创建了一个空的对象 // 2.this就会指向刚才创建的空对象 // 3.执行构造函数里面的代码 给这个空对象添加属性和方法 // 4.返回这个新对象(所以构造函数里面不需要return)

    2024年02月06日
    浏览(42)
  • 【Servlet学习三】实现一个内存版本的简易计算器~

    目录 一、方式1:使用form表单的形式(不推荐) 🌈1、前端代码:HTML文件 🌈2、后端代码:Calculator_form.java文件 🌈3、最终效果 二、方式2:使用ajax形式(最常用重点!!!) 🌈1、前端代码:HTML文件 🌈2、后端代码:Calculator_ajax.java文件 🌈3、最终效果  注意: (1)前端

    2024年02月12日
    浏览(31)
  • OpenHarmony开发实战:简易计算器(ArkTS)

    本篇Codelab基于基础组件、容器组件,实现一个支持加减乘除混合运算的计算器。   说明:  由于数字都是双精度浮点数,在计算机中是二进制存储数据的,因此小数和非安全整数(超过整数的安全范围[-Math.pow(2, 53),Math.pow(2, 53)]的数据)在计算过程中会存在精度丢失的情况

    2024年04月29日
    浏览(45)
  • Android 从零开发一个简易的相机App

    本文介绍了实现一个简易Android相机App过程中,遇到的一些问题,对Camera API的选型、通知相册更新、跳转相册、左右滑动界面切换拍照/录像,相机切换时候的高斯模糊虚化效果、相机切换的3D效果做了说明。 Android调用相机可以使用 Camera1 、 Camera2 和 CameraX 1.1 Camera1 Camera1 的

    2024年02月12日
    浏览(36)
  • Web前端开发 小实训(二) 简易计算器

    学生能够使用函数完成简易计算器编写 中文 英语 加法 add 减法 subtract 乘法 multi 除法 division 次幂 pow() 平方根 sqrt() 提示: 除法中的除数不能为0! 参考代码: 参考代码 步骤3-4参考代码 申明方法后,在每个分支后调用 最后直接调用运行页面 因面向的是初学Web前端课程的学生

    2024年04月28日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包