用 Kotlin 构建小费计算器:它是如何工作的?

用 Kotlin 构建小费计算器:它是如何工作的?

我们向您展示如何在 Kotlin 中创建简单的小费计算应用程序。 更准确地说,是 Kotlin 1.3.21、Android 4、Android Studio 3。首先,对于那些开始开发 Android 应用程序的人来说,这篇文章会很有趣。 它可以让您了解应用程序内部的内容和工作方式。

当您需要计算决定在餐厅或咖啡馆消磨时间的公司的小费金额时,这样的计算器非常有用。 当然,并不是每个人,也不总是给服务员留茶,这更多的是西方的传统,但无论如何,开发这样一个应用程序的过程很有趣。

我们提醒: 对于“Habr”的所有读者 - 使用“Habr”促销代码注册任何 Skillbox 课程可享受 10 卢布的折扣。

技能箱推荐: 实践课程 “移动开发者专业版.

该应用程序运行时的外观如下:

用 Kotlin 构建小费计算器:它是如何工作的?

您输入所需的总金额百分比、会议参与者人数,然后得到结果 - 应该留下的小费金额。

入门

该应用程序的完整界面如下所示:
用 Kotlin 构建小费计算器:它是如何工作的?

用 Kotlin 构建小费计算器:它是如何工作的?

第一个动作—— 项目库下载。 在 Android Studio 3.0 或更高版本中打开它。 我们构建并运行该项目并看到一个白屏。 一切都很好,应该如此。

用 Kotlin 构建小费计算器:它是如何工作的?

用 Kotlin 构建小费计算器:它是如何工作的?

用户操作按照时间顺序写在项目中,这样一切都一目了然。 要查看它,请打开视图 -> 工具窗口 -> TODO。

我们研究该项目并打开colors.xml 来评估调色板。 strings.xml 包含文本数据(标题),styles.xml 包含多个字体模板。

成本部分开发

打开 Activity_main.xml 并将以下代码添加到 LinearLayout (#1):

<TextView
    android_id="@+id/expensePerPersonTextView"
    android_layout_width="match_parent"
    android_layout_height="wrap_content"
    android_paddingTop="30dp"
    style="@style/h1Bold"
    android_textColor="@color/colorAccent"
    android_text="0"/>
 
<TextView
    android_layout_width="match_parent"
    android_layout_height="wrap_content"
    android_paddingBottom="25dp"
    style="@style/h2"
    android_textColor="@color/colorAccent"
    android_text="@string/perPersonStaticText"/>

现在您可以使用以下命令设置值目录的样式或使用颜色 Material.io 工具.

现在该项目如下所示:

用 Kotlin 构建小费计算器:它是如何工作的?
正如您所看到的,成本计算是基于用户输入的数据。

账户部分的开发

将以下代码添加到 LinearLayout 的费用部分 (#2) 之后:

<LinearLayout
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_orientation="vertical"
    android_background="@color/colorAccent">
 
<! — TODO #3: Build Bill Section →
 
… 
</LinearLayout>

关闭 TODO 列表后的 LinearLayout,然后添加新代码,将其放置在 LinearLayout 中 (#3):

<TextView
      android_layout_margin="15dp"
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_textColor="@color/colorWhite"
      style="@style/h4"
      android_text="@string/billStaticText"/>
 
<EditText
      android_id="@+id/billEditText"
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_textColor="@color/colorWhite"
      android_inputType="numberDecimal"
      android_maxLines="1"
      style="@style/h2Bold"
      android_text="0"/>

由于该应用程序的主要任务是计算餐厅聚会中每个参与者的个人费用,因此 costPerPersonTextView 起着主要作用。

EditText 限制输入一行,该参数必须设置为 NumberDecimal inputType。

用 Kotlin 构建小费计算器:它是如何工作的?
我们启动项目进行测试并输入总损坏的参数(破碎的杯子、盘子等)

开发“人员和提示”部分

要添加小费金额选择器,请将以下代码粘贴到新的 LinearLayout 部分 (#4):

<TextView
      android_layout_margin="15dp"
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_textColor="@color/colorWhite"
      style="@style/h4"
      android_text="@string/tipStaticText"/>
 
<LinearLayout
      android_layout_width="match_parent"
      android_layout_height="wrap_content"
      android_orientation="horizontal">
 
<ImageButton
        android_id="@+id/subtractTipButton"
        style="@style/operationButton"
        android_layout_marginLeft="20dp"
        android_layout_marginStart="20dp"
        android_src="@drawable/subtract"/>
 
<TextView
        android_id="@+id/tipTextView"
        android_layout_margin="15dp"
        android_layout_width="0dp"
        android_layout_height="wrap_content"
        android_textColor="@color/colorWhite"
        android_layout_weight="1"
        style="@style/h2Bold"
        android_text="20%"/>
 
<ImageButton
        android_id="@+id/addTipButton"
        style="@style/operationButton"
        android_layout_marginEnd="20dp"
        android_layout_marginRight="20dp"
        android_src="@drawable/add"/>
 
</LinearLayout>

需要这段代码来准确计算小费金额。 默认文本值为 20。ImageButtons 是在具有写入权限的文件夹中提供的图标。

复制整个部分并添加以下内容 (#5):

  • ImageButton id (subtractPeopleButton, addPeopleButton)
  • TextView id (numberOfPeopleStaticText, numberOfPeopleTextView)
  • numberOfPeopleTextView 的 DefaultText(应为 4)。

用 Kotlin 构建小费计算器:它是如何工作的?

现在,启动应用程序时,可以添加发票金额,“添加/减去”按钮也可以工作,但到目前为止没有任何反应。

添加视图

打开 MainActivity.kt 并将其添加到 initViews 函数中 (#6):

private fun initViews() {
        expensePerPersonTextView = findViewById(R.id.expensePerPersonTextView)
        billEditText = findViewById(R.id.billEditText)
 
addTipButton = findViewById(R.id.addTipButton)
        tipTextView = findViewById(R.id.tipTextView)
        subtractTipButton = findViewById(R.id.subtractTipButton)
 
addPeopleButton = findViewById(R.id.addPeopleButton)
        numberOfPeopleTextView = findViewById(R.id.numberOfPeopleTextView)
        subtractPeopleButton = findViewById(R.id.subtractPeopleButton)
 
//TODO #8: Bind Buttons to Listener
 
//TODO #16: Bind EditText to TextWatcher
 
}

完成按钮

要添加对按钮单击的支持,请在类级别实现 View.OnClickListener (#7):

类 MainActivity: AppCompatActivity(), View.OnClickListener {

现在编译项目将无法工作,您需要执行更多步骤(#8):

override fun onClick(v: View?) {
        when (v?.id) {
            R.id.addTipButton -> incrementTip()
            R.id.subtractTipButton -> decrementTip()
            R.id.addPeopleButton -> incrementPeople()
            R.id.subtractPeopleButton -> decrementPeople()
        }
    }

在按钮和开关方面,Kotlin 的一切组织得非常酷! 将以下代码添加到所有递增和递减函数中
(#9 –#12):

private fun incrementTip() {
        if (tipPercent != MAX_TIP) {
            tipPercent += TIP_INCREMENT_PERCENT
            tipTextView.text = String.format("%d%%", tipPercent)
        }
    }
 
private fun decrementTip() {
        if (tipPercent != MIN_TIP) {
            tipPercent -= TIP_INCREMENT_PERCENT
            tipTextView.text = String.format("%d%%", tipPercent)
        }
    }
 
private fun incrementPeople() {
        if (numberOfPeople != MAX_PEOPLE) {
            numberOfPeople += PEOPLE_INCREMENT_VALUE
            numberOfPeopleTextView.text = numberOfPeople.toString()
        }
    }
 
private fun decrementPeople() {
        if (numberOfPeople != MIN_PEOPLE) {
            numberOfPeople -= PEOPLE_INCREMENT_VALUE
            numberOfPeopleTextView.text = numberOfPeople.toString()
        }
    }

这里的代码保护具有最大值的增量函数(MAX_TIP & MAX_PEOPLE)。 此外,代码还保护具有最小值的减量函数(MIN_TIP & MIN_PEOPLE)。

现在我们将按钮绑定到 initViews 函数中的侦听器 (#13):

private fun initViews() {
 
...
 
addTipButton.setOnClickListener(this)
        subtractTipButton.setOnClickListener(this)
 
addPeopleButton.setOnClickListener(this)
        subtractPeopleButton.setOnClickListener(this)
 
//TODO #15: Bind EditText to TextWatcher
}

用 Kotlin 构建小费计算器:它是如何工作的?

您现在可以添加总伤害、提示和会议参与者的数量。 嗯,现在最重要的是...

成本部分

此代码计算成本(#14):

private fun calculateExpense() {
 
val totalBill = billEditText.text.toString().toDouble()
 
val totalExpense = ((HUNDRED_PERCENT + tipPercent) / HUNDRED_PERCENT) * totalBill
        val individualExpense = totalExpense / numberOfPeople
 
expensePerPersonTextView.text = String.format("$%.2f", individualExpense)
 
}

好吧,这里调用了一个函数,可以考虑公司的人数并计算小费(#15):

private fun incrementTip() {
 
…
 
}
 
private fun decrementTip() {
 
…
 
}
 
private fun incrementPeople() {
 
…
 
}
 
private fun decrementPeople() {
 
…
 
}

我们启动该应用程序。 它看起来和工作都很棒。 但它可能会更好。

如果您尝试删除账单金额,然后增加提示或朋友的数量,应用程序将崩溃,因为尚未检查零成本。 此外,如果您尝试更改发票金额,费用将不会更新。

最后步骤

添加文本观察器(#16):

类MainActivity:AppCompatActivity(),View.OnClickListener,TextWatcher {

然后我们嵌入 billEditText 监听器(#17):

billEditText.addTextChangedListener(this)

添加代码来执行 TextWatcher (#18):

override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (!billEditText.text.isEmpty()) {
            calculateExpense()
        }
    }
override fun afterTextChanged(s: Editable?) {}

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

用 Kotlin 构建小费计算器:它是如何工作的?

好吧,现在一切正常了! 恭喜,您已经用 Kotlin 编写了自己的“小费计算器”。

用 Kotlin 构建小费计算器:它是如何工作的?

技能箱推荐:

来源: habr.com

添加评论