DadEap Purple
DadEap Purple

Reputation: 91

Strange CheckBox Behaviour

I wanted to use a checkBox to change a textView's message. When the checkBox is checked, it show the text "checked", if not, the text "unchecked".

I used a onClickListener, and everything seems to work until ... I switched to landscape : if the checkBox was checked, the checkBox stays checked, while it should be unchecked as the activity is recreated and his starting value is "false".

I dig in a little and saw the value of the checkBox was, as expected, "false".

Illustration with code :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
    final TextView textView = (TextView) findViewById(R.id.textView1);

    //Code to check if checkbox is checked
    if (checkBox.isChecked())
        textView.setText("Checked");

    checkBox.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (checkBox.isChecked()) {
                textView.setText("Checked");
            }else 
                textView.setText("Unchecked");
        }
    });
}

Starting screen :

enter image description here

Checked :

enter image description here

Switch to Landscape :

enter image description here

The activity is created again, checkBox value is false, but it appears like it is checked !

The question is then :

why does the checkbox show on the screen like it is checked ?

Upvotes: 1

Views: 123

Answers (2)

Tim Kruichkov
Tim Kruichkov

Reputation: 1493

also suitable for my situation with Switch

Upvotes: 0

CodeBlake
CodeBlake

Reputation: 184

disable restoring instance state applying to this checkbox

add android:saveEnabled="false" to your checkbox xml

Upvotes: 2

Related Questions