简体   繁体   中英

Saving state _before_ orientation change when android:configChanges=“orientation” is specified

I have an Activity in my Android app that sets different layout XMLs as its view depending on the orientation. I have declared android:configChanges="orientation" in the manifest. Now onConfigurationChanged() is called - but by this time the new orientation has already taken effect.

My goal is to try to hook into the life cycle and try to save some changes before the new orientation is in effect; so that I can restore the state when I return to the current orientation.

I hacked it as follows, but I'm not sure if this is the right way to do this. My procedure involves saving the state in onConfigurationChanged() and then calling setContentView() to set the layout for the new orientation.

public class SwitchOrientationActivity extends Activity {

    private View mLandscape, mPortrait;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater li = LayoutInflater.from(this);
        mLandscape = li.inflate(R.layout.landscape, null);
        mPortrait = li.inflate(R.layout.portrait, null);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (Configuration.ORIENTATION_LANDSCAPE == newConfig.orientation) {
            switchToLandscape();
        } else {
            switchToPortrait();
        }
    }

    private void switchToPortrait() {

        /*
         * Use mLandscape.findViewById() to get to the views and save the values
         * I'm interested in.
         */
        saveLanscapeState();
        setContentView(mPortrait);
    }

    private void switchToLandscape() {
        /*
         * Use mPortrait.findViewById() to get to the views and save the values
         * I'm interested in.
         */
        savePortraitState();
        setContentView(mLandscape);

    }
}

Is there a more elegant way to achieve this?

android:configChanges="orientation" causes your activity to not be restarted on an orientation change, and so skips the regular lifecycle for this. I'd suggest, you take that out, then implement onRetainNonConfigurationInstance () and restore your state in either onCreate or onRestoreInstanceState. See this article for more info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM