Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Menu Options checkboxes unchecked on orientation change fix

In my app, when options are checked in the overflow menu, then the orientation is changed, they become unchecked. Any way to fix this? I know onSavedInstance should be able to help me here, but I don't know how to implement it in my case.

Here's an Example of how my overflow checkboxes are handled in the main activity

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}



@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {


switch (item.getItemId()) {

case R.id.subtract_option:
    if (item.isChecked()){
        item.setChecked(false);
        subtractMode = false;

    } else{
        item.setChecked(true);
        subtractMode = true;
    }

    return true;

default:
    return super.onMenuItemSelected(featureId, item);

So how would I implement the onSavedInstanceState in this case?

like image 595
Alex Avatar asked Dec 06 '25 05:12

Alex


1 Answers

It has to do with how Android handles orientation changes. It actually kills your activity and restarts it. There's two ways to fix it.

1)Implement onSaveInstanceState, write all your state to an object (including the values of checkboxes) and implement onRestoreInstanceState to reverse the process.

2)Add android:configChanges="orientation". This will stop the overriding behavior. It will also break the automatic reloading of layouts if you have separate landscape andd portrait layouts.

I recommend route 2 if your don't have separate layouts for the orientations. If you do and your app is simple, I suggest route 1. If you need that and your app is complex you're screwed and in for a world of pain.

like image 132
Gabe Sechan Avatar answered Dec 07 '25 22:12

Gabe Sechan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!