Home > Software engineering >  How can I fix this? cant put setError to my editText
How can I fix this? cant put setError to my editText

Time:04-28

I make my first android app with Android Studio, and now I want to make a setError on my editText, but I cant, I only can put a toast here is my code:

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    binding.calculateButton.setOnClickListener { calculateTip() }
}

private fun calculateTip() {
    val stringInTextField = binding.costOfProduct.text.toString()
    val stringInTextField1 = binding.amountOfProduct.text.toString()
    if (stringInTextField.isEmpty()) {
        Toast.makeText(this, "this cant be empty", Toast.LENGTH_SHORT).show()
        return
    }
    val cost = stringInTextField.toDouble() / stringInTextField1.toDouble()
    val tipPercentage = when (binding.productOptions.checkedRadioButtonId) {
        R.id.option_normal -> 1.5
        R.id.option_60 -> 1.6
        R.id.option_70 -> 1.7
        else -> 2.0
    }
    var product = tipPercentage * cost
    val roundUp = binding.IVA.isChecked
    if (roundUp) {
        product = (tipPercentage * cost) * 1.21
    }
    val formattedTip = NumberFormat.getCurrencyInstance().format(product)
    binding.result.text = getString(R.string.resultado, formattedTip)
}

}

CodePudding user response:

You should use to setError()

Like this: stringInTextField.setError("this cant be empty")

For more information: Show Error on the tip of the Edit Text Android

CodePudding user response:

you can use this following code according to your code:

if (stringInTextField.isEmpty()) { stringInTextField.setError("this cant be empty") return; }

  • Related