Android – 使功能为false /不运行
我有两个按钮上的setOnClickListener
,它们只是在两个函数中运行代码。
我想创建一个安全的电话,所以当我点击按钮的应用程序不会崩溃。 我以为我不得不让他们虚假或什么,但显然这是行不通的。
我应该怎么做?
谢谢
if (weightView.text.isEmpty() && percentageView.text.isEmpty()) { calculation() == false lbsCalculation() == false } else { calculation() lbsCalculation() }
这些是我的两个clickListeners
calculateBtn.setOnClickListener{ calculation() } lbsCalculationBtn.setOnClickListener{ lbsCalculation() }
功能:
fun calculation () { var weightValue = weightView.text.toString().toInt() var percentageValue = percentageView.text.toString().toInt() var result = (weightValue * percentageValue) / 100.toDouble() var resultFormat = "%.1f KG".format(result) resultView.text = resultFormat.toString() } fun lbsCalculation() { var weightValue = weightView.text.toString().toInt() var percentageValue = percentageView.text.toString().toInt() var result = ((weightValue * percentageValue) / 100) * 2.2.toDouble() var resultFormat = "%.1f LBS".format(result) resultView.text = resultFormat.toString() }
=================
图片
- 添加一个Fragment后,Android工作室分解了我的build.gradle文件
- 我可以导入一个库在Kotlin写入我的Android项目(使用Java)
- 将Kotlin添加到现有Java项目会打破Android Studio gradle消息错误
- 类型不匹配:推断类型是FragmentActivity? 但是在将支持库更新到27.0.0时预期上下文
- Firebase:在Kotlin / Java中使用枚举字段的干净方式?
在你的方法里面做。 像这样的东西:
public class calculation(String weightView, String percentageView){ //you make a condition that should do something if strings are empty if(weightView && percentageView == null) //DO WHAT YOU WANT }else{ //Show an alert or something that your EditText is empty. }
应该像这样调用它:
calculateBtn.setOnClickListener{ calculation(weightView.getText.toString(),percentageView.getText.toString()) }
======编辑=======
你的功能应该是这样的:
fun calculation(weightValue: String,percentageValue: String) { if(weightValue == null && percentageValue == null ){ var myWeightValue = weightValue.toInt(); var myPercentageValue = percentageValue.toInt(); var result = (myWeightValue * myPercentageValue) / 100 var resultFormat = "%.1f KG".format(result) resultView.text = resultFormat } else { **SHOW A MESSAGE LIKE A TOAST OR ALERTDIALOG TO LET THE USER KNOW THAT WEIGHT AND PERCENTAGE IS REQUIRED** } } fun lbsCalculation() { var weightValue = weightView.text.toString().toInt() var percentageValue = percentageView.text.toString().toInt() var result = ((weightValue * percentageValue) / 100) * 2.2 var resultFormat = "%.1f LBS".format(result) resultView.text = resultFormat }
你的onClick应该是这样的:
calculateBtn.setOnClickListener{ calculation(weightView.text,percentageView.text) }