Tuesday, February 28, 2012

Faster Screen Orientation Change resolve problem

The Activity class has a special method called onRetainNonConfigurationInstance(). This method can be used to pass an arbitrary object to your future self and Android is smart enough to call this method only when needed. In the case of Photostream, the application used this method to pass the downloaded images to the future activity on orientation change. The implementation can be summarized like so:

@Override
public Object onRetainNonConfigurationInstance() {
final LoadedPhoto[] list = new LoadedPhoto[numberOfPhotos];
keepPhotos(list);
return list;
}

In the new activity, in onCreate(), all you have to do to get your object back is to call getLastNonConfigurationInstance(). In Photostream, this method is invoked and if the returned value is not null, the grid is loaded with the list of photos from the previous activity:

private void loadPhotos() {
final Object data = getLastNonConfigurationInstance();

// The activity is starting for the first time, load the photos from Flickr
if (data == null) {
mTask = new GetPhotoListTask().execute(mCurrentPage);
} else {
// The activity was destroyed/created automatically, populate the grid
// of photos with the images loaded by the previous activity
final LoadedPhoto[] photos = (LoadedPhoto[]) data;
for (LoadedPhoto photo : photos) {
addPhoto(photo);
}
}
}

No comments:

Post a Comment