已经解决了,原来是没给按钮加tag
(¦3[▓▓]记录一下吧
编写计算器程序的时候出现了闪退,所以没有写完,只有一部分功能,大概是:
希望在点击数字按钮的时候,第一行TextView能够显示点击的数字,并在点击第二个数字时与前一个数字进行拼接显示。
虽然是照着别人做的,但是由于kotlin-android-extensions插件被废止了,所以我做的时候就不能直接引用xml中的id,只好现学用ViewBinding来代替findViewById的工作。
虽然程序没报错,却在点击按钮时出现了闪退,求帮助,以下是我的MainActivity的代码。
class MainActivity : ComponentActivity() {
private lateinit var binding:ActivityMainBinding
var num1: StringBuilder = StringBuilder()
var num2: StringBuilder = StringBuilder()
lateinit var operation: String //还没用
var isFirstNumber: Boolean = true
var currentOperation: String? = null //还没用
var details: StringBuilder = StringBuilder()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.oneBtn.setOnClickListener {
numClicked(it)
}
binding.twoBtn.setOnClickListener {
numClicked(it)
}
binding.threeBtn.setOnClickListener {
numClicked(it)
}
binding.fourBtn.setOnClickListener {
numClicked(it)
}
binding.fiveBtn.setOnClickListener {
numClicked(it)
}
binding.sixBtn.setOnClickListener {
numClicked(it)
}
binding.eightBtn.setOnClickListener {
numClicked(it)
}
binding.nineBtn.setOnClickListener {
numClicked(it)
}
binding.zeroBtn.setOnClickListener {
numClicked(it)
}
}
fun numClicked(view: View){
var numString = view.tag as String
if(isFirstNumber){
num1.append(numString) //把数加在操作符前的数后
details.append(numString)
}
else{
num2.append(numString)
details.append(numString)
}
binding.progressTextView.text = "$details" //展示字符串
}
还有日志,理解不了T_T
20:53:16.168 E FATAL EXCEPTION: main
Process: com.example.mycalculator, PID: 8819
java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String
at com.example.mycalculator.MainActivity.numClicked(MainActivity.kt:62)
at com.example.mycalculator.MainActivity.onCreate$lambda$4(MainActivity.kt:44)
at com.example.mycalculator.MainActivity.$r8$lambda$UgAc9_AiizbUhm38KbDJtqxZQWI(Unknown Source:0)
at com.example.mycalculator.MainActivity$$ExternalSyntheticLambda4.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
20:53:16.192 I Sending signal. PID: 8819 SIG: 9
20:53:16.291 E channel '7145893 com.example.mycalculator/com.example.mycalculator.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!