Enabling EditText when a radiobutton is checked

Try to use a RadioButton listener outside you calculateTip() method, see the following code:

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()}
    binding.costOfServiceEditText.setOnKeyListener { view, keyCode, _ -> handleKeyEvent(view, keyCode) }
    
    //adding listener and manipulate editText
    val EditText = binding.customPercent
    radio_group.setOnCheckedChangeListener(
            RadioGroup.OnCheckedChangeListener { group, checkedId ->
                when (binding.tipOptions.checkedRadioButtonId) {
                R.id.option_fifteen_percent -> EditText.isEnabled = false
                R.id.option_eighteen_percent -> EditText.isEnabled = false
                R.id.option_twenty_percent -> EditText.isEnabled = false
                else -> EditText.isEnabled = true }
         }
      )
   }

private fun calculateTip(){
val stringInTextField = binding.costOfServiceEditText.text.toString()
val cost = stringInTextField.toDoubleOrNull()



if (cost == null){
    binding.tipResult.text = ""
    binding.costOfService.hint = "Insira o valor aqui"
    return
}

val customPercent = binding.customPercent.getText().toString().toDouble()
val customPercentOption = customPercent / 100

val tipPercentage = when (binding.tipOptions.checkedRadioButtonId) {
    R.id.option_twenty_percent -> 0.20
    R.id.option_eighteen_percent -> 0.18
    R.id.option_fifteen_percent -> 0.15
    else -> customPercentOption

}

var tip = tipPercentage * cost
val roundUp = binding.roundUpSwitch.isChecked
if (roundUp) {
    tip = kotlin.math.ceil(tip)
}

NumberFormat.getCurrencyInstance()
    val formattedTip = NumberFormat.getCurrencyInstance().format(tip)
    binding.tipResult.text = getString(R.string.tip_amount, formattedTip)

}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top