Android 如何在文本框中获取用户输入,并使用它在Kotlin中执行数学运算?
我正在开发一个android应用程序,用于计算员工的佣金。我不知道如何调用用户输入并使用它来执行数学运算。我希望他们输入每个字段中的所有数字,然后单击“计算”按钮。这将调用第一个输入字段并将其乘以5,然后调用第二个输入字段并将其乘以7.5等,直到所有六个用户输入字段都乘以一个设定的数字,然后将它们全部相加并转储到“支付”字段中。我似乎找不到一个开始的地方。如果有人能让我走上正确的道路,我将不胜感激。下面的代码片段提供了一点额外的上下文Android 如何在文本框中获取用户输入,并使用它在Kotlin中执行数学运算?,android,xml,kotlin,Android,Xml,Kotlin,我正在开发一个android应用程序,用于计算员工的佣金。我不知道如何调用用户输入并使用它来执行数学运算。我希望他们输入每个字段中的所有数字,然后单击“计算”按钮。这将调用第一个输入字段并将其乘以5,然后调用第二个输入字段并将其乘以7.5等,直到所有六个用户输入字段都乘以一个设定的数字,然后将它们全部相加并转储到“支付”字段中。我似乎找不到一个开始的地方。如果有人能让我走上正确的道路,我将不胜感激。下面的代码片段提供了一点额外的上下文 <Button android:id=
<Button
android:id="@+id/button"
android:layout_width="207dp"
android:layout_height="0dp"
android:layout_marginBottom="17dp"
android:text="@string/calculate"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextNumber7" />
<EditText
android:id="@+id/editTextNumber7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:ems="10"
android:hint="@string/payout"
android:importantForAutofill="no"
android:inputType="number"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextNumber4" />
在您的kotlin类中,您应该找到按钮和每个编辑文本的id:
val button = findViewById<Button>(R.id.button)
//...
val editText7 = findViewById<EditText>(R.id.editTextNumber7)
要从特定editText获取文本,应执行以下操作:
val text7 = editText7.text
要将其转换为int,请执行以下操作:
val number7 = text7.toString().toInt()
嘿,谢谢你的指导!到第三段代码之前,我已经完成了所有的工作,我正在研究如何进行整数转换。出于好奇,如果用户只能输入整数,我需要转换还是继续计算?@BlakeWord抱歉,我忘了解释这个问题
editText.text
正在返回Editable
,因此要将文本作为字符串获取,需要执行editText.text.toString()
,如果需要inteditText.text.toString().toInt()
,非常感谢您的帮助!你让我走上了正确的道路,我今天完成了完整的产品。非常感谢!
val number7 = text7.toString().toInt()