【发布时间】:2021-08-17 05:25:13
【问题描述】:
我目前拥有所有需要的按钮。但是,Operators 按钮没有使用该字符。在您单击其中一个运算符时,不会返回任何内容。
package com.example.mycalculator
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
var lastNumeric : Boolean = false
var lastDot : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun onDigit(view: View){
tvInput.append((view as Button).text)
lastNumeric = true
}
fun onClear(view: View){
tvInput.text = ""
lastNumeric = false
lastDot = false
}
fun onDecimalPoint(view: View){
if (lastNumeric && !lastDot){
tvInput.append(".")
lastNumeric = false
lastDot = false
}
}
fun onEqual(view: View){
if(lastNumeric){
var tvValue = tvInput.text.toString()
var prefix = "="
try {
if(tvValue.contains("-")){
val splitValue = tvValue.split("-")
var one = splitValue[0]
var two = splitValue[1]
if(!prefix.isEmpty()){
one = prefix + one
}
// Check if it is empty or if we have a second minus
tvInput.text = (one.toDouble() - two.toDouble()).toString()
} else if(tvValue.contains("/")){
val splitValue = tvValue.split("/")
var one = splitValue[0]
var two = splitValue[1]
// Check if it is empty or if we have a second minus
if(!prefix.isEmpty()){
one = prefix + one
}
tvInput.text = (one.toDouble() / two.toDouble()).toString()
}else if(tvValue.contains("*")){
val splitValue = tvValue.split("*")
var one = splitValue[0]
var two = splitValue[1]
// Check if it is empty or if we have a second minus
if(!prefix.isEmpty()){
one = prefix + one
}
tvInput.text = (one.toDouble() * two.toDouble()).toString()
}else if(tvValue.contains("+")){
val splitValue = tvValue.split("+")
var one = splitValue[0]
var two = splitValue[1]
// Check if it is empty or if we have a second minus
if(!prefix.isEmpty()){
one = prefix + one
}
tvInput.text = (one.toDouble() + two.toDouble()).toString()
}
}catch (e: ArithmeticException){
e.printStackTrace()
}
}
}
fun onOperator(view: View){
if(lastNumeric && !isOperatorAdded(tvInput.toString())){
tvInput.append((view as Button).text)
lastNumeric = false
}
}
private fun isOperatorAdded(value: String) : Boolean {
return if (value.startsWith("-")){
false
} else value.contains("/") || value.contains("*") || value.contains("+") || value.contains("-")
}
}
在 activity_main 内部,我知道操作员是通过 onClick 元素调用“onOperator”来的。
例子:
<Button
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:width="0dp"
android:text="+"
android:onClick="onOperator"
android:layout_margin="5dp"
/>
有谁知道解决这个问题的最佳方法是什么?
【问题讨论】:
-
什么都没有返回是什么意思? 1、代码流是否调用
onOperator方法? 2.你的If条件成功了吗? 3. 有没有加断点,检查作用域内view的值是多少? -
我可以尽可能多地点击每个数字,但其他所有内容都不可见。以下运算符不可见(+、-、*、/)
标签: android kotlin android-layout