Skip to content Skip to sidebar Skip to footer

Gracefully Handling Screen Orientation Change During Activity Start

I'm trying to find a way to properly handle setting up an activity where its orientation is determined from data in the intent that launched it. This is for a game where the user c

Solution 1:

You could make two Activities - one for portrait levels, the other for landscape levels - and then set the Activity's orientation in AndroidManifest.xml, using the android:screenOrientation attribute. You won't even have to duplicate code if you use inheritance; use your current Activity as the base activity, and just create the landscape/portrait Activities as subclasses of that Activity.

I think a better solution would be for the Intent to open the correct Activity of these two, though if you must have everything be routed via Intent extra analysis, you could forward all levels to a third Activity that does nothing more than analyse the Intent and then forward it to the proper Activity.

Solution 2:

You could also override onRetainNonConfigurationInstance(). This lets you temporarily store one item that you can retrieve by calling getLastNonConfigurationInstance(). That way you can load all of the stuff that you need and in your onRetainNonConfigurationInstance() method you can save it all into a data structure and return it. The in your onCreate() you can call getLastNonConfigurationInstance() and if that returns null load, load all of your stuff, if it return something, then you have it all loaded. Here's a quick example:

publicclassMyActivityextendsActivity
{
    @OverridepublicvoidonCreate(Bundle savedInstanceState)
    {
        DataStructuremyData= (DataStructure)getLastNonConfigurationInstance();
        if(myData == null)
        {
            // Load everything in
        }
        else
        {
            // Unpack myData
        }
    }

    @Overridepublic Object onRetainNonConfigurationInstance()
    {
        DataStructuremyData=newDataStructure();
        // Put everything in to myDatareturn myData;
    }
}

Post a Comment for "Gracefully Handling Screen Orientation Change During Activity Start"