1

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 ?

2 Answers2

2

disable restoring instance state applying to this checkbox

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

CodeBlake
  • 194
  • 3
  • 13
  • the restoredInstanceState bundle is usually not thought about and overrides recreation when it comes to xml sheets with a higher priority then your backend work, and is usually the issue when running into issues such as these – CodeBlake Jul 08 '14 at 15:34
0

also suitable for my situation with Switch

Tim Kruichkov
  • 1,473
  • 1
  • 14
  • 19