Question

According to references, ToggleButtons and Switches are supposed to be used with an OnCheckedChangeListener or with a function like onToggleClicked(View view).

However, both ways return void and the inner if statement, which is either if (on) or if (checked), or if (isChecked), doesn't let me to set a usable variable. The same applies for radio buttons.

I have an app where I'd like to calculate daily energy requirements of intensive care patients. I need to use multiple switches; and all these selectors jointly affect a calculation. An example formula is:

1784 + (5 * weight) - (11 * age) + (244 if male) + (239 if trauma patient) + (804 if burn patient)

Below is an example including a single switch. Ididn't include my solution for all the switches/parameters, since that's too many code clutter:

public double calculateBMI(View view) {
  EditText getHeight = (EditText)findViewById(R.id.height);  // find the widget
  String height_as_string = getHeight.getText().toString();  // get the string
  int height = Integer.parseInt(height_as_string);           // convert to integer    

  Switch gender = (Switch)findViewById(R.id.gender);         // find the switch

  double heightConvertedToInch = height / 2.54;  // convert height to inch
  // calculate ideal body weight        
  if(gender.isChecked()){                        // gender is male
    double idealBodyWeight = 106 + ( 6 * heightConvertedToInch );
    return idealBodyWeight;
  } else {                                       // gender is female
    double idealBodyWeight = 100 + ( 5 * heightConvertedToInch );
    return idealBodyWeight;
  }
}
Was it helpful?

Solution

According to references, ToggleButtons and Switches are supposed to be used with an OnCheckedChangeListener or with a function like onToggleClicked(View view).

Those are event listeners, if you need to take immediate action based upon the change of the state of the compound button, such as enabling/disabling other widgets. They are not needed otherwise.

What is the proper way to handle this situation?

Call isChecked() on each CompoundButton (whether ToggleButton or Switch or CheckBox or whatever), and use that information to "affect a calculation".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top