Posts tagged Orientation

Android

Android: Retain values on orientation change

0

When you change the orientation of your phone. The current activity is destroyed via onDestroy() and then recreated with onCreate() being called. This presented a problem for me with a list that has different ways of sorting – I wanted this sorted order to persist while the current activity was open, but there was no need for it to do so when coming to the activity again. Here’s a quick demonstration of how to achieve this.

The type of sort to do is stored in a member variable. This uses constants from my Database Adapter class. When the data is pulled from the database, this sort code is passed in and used by the DB Adapter, data is returned sorted correctly. When the phone’s orientation is changed we want the list to remain sorted in the same order.

private Integer mListSortCode;

Next in your activity, override onRetainNonConfigurationInstance(). This method is called just before onDestroy(). In my example I need only one value so I made the mListSortCode an Integer object. It’s easy to see how you could create an inner class that would hold all the data you need to retain and use it here.

@Override
public Object onRetainNonConfigurationInstance() {
    final Integer sortcode = mListSortCode;
    return sortcode;
}

In your onCreate() method call getLastNonConfigurationInstance() to get a reference to this object and cast it to the correct type. If onCreate() is being called because of any reason other than an orientation change it will be null, so check for this and handle appropriately:

final Integer previousConfigSortCode = (Integer)getLastNonConfigurationInstance();
if (previousConfigSortCode != null) {
    mListSortCode = previousConfigSortCode;
} else {
    //set to default
    mListSortCode = SpecimenHunterDatabaseAdapter.SORT_NONE;
}

 

Android

Android: Lock and unlock screen orientation

15

Need to temporarily lock the screen orientation on your app? When calling setRequestedOrientation() on your activity, it will no longer allow the orientation to change even when the phone is rotated. So check what the current orientation of the screen is and set it to the same orientation with setRequestedOrientation()

public static void lockCurrentScreenOrientation(Activity a) {

	if(a.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
		a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	} else {
		a.setRequestedOrientation(a.getRequestedOrientation());
	}
}

To unlock it again, pass ActivityInfo.SCREEN_ORIENTATION_USER:

public static void unlockScreenOrientation(Activity a) {
	a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
}
Go to Top