mercredi 16 novembre 2016

Getting the isChecked() value from CheckBox or RadioButton

I have set the click event listener on a number of CheckBox and RadioButton views. Both of these view types have an isChecked() method. I can get the state of either one by casting to its type for every single switch case, but can I get the state just in a general sense for either of them before I enter the switch cases?

@Override
public void onClick(View view) {

    boolean checkState;

    switch (view.getId()) {
        case R.id.radio_button_1:
            checkState = ((RadioButton) view).isChecked();
            // ...
            break;
        case R.id.check_box_1:
            checkState = ((CheckBox) view).isChecked();
            // ...
            break;
        // more check boxes and ratio buttons ...
    }
}

This question has a similar title to this one, but there was too much code there for me to easily understand if they were asking the same thing.

While I was in the process of writing this question, I found an answer, which I will post below. However, if there is a better answer, I will accept it.




Aucun commentaire:

Enregistrer un commentaire