Monday, January 19, 2015

Android - Handling Configuration Changes Yourself

There are many things that can happen outside of your Android application. One of the most common occurrences is a change in the device settings. For example, the user might leave your app running, while they go into the display settings and change the font size.

Android Font Size Setting

When the user goes back to your application, the activity in your application is recreated, which means onCreate() is called all over again. Most times, this is o.k. In fact, for the most part, you want to trust Android to handle these global settings and manage the effects of those changes to the lifecycle of your application's activities. However, there are times when you may want to manually handle these configuration changes. One obvious advantage to manually handling the config changes, is that you can avoid the activity being killed and recreated. Note that onStart(), onResume(), and onRestart() will still be called.

To manually handle config changes, simply add the "android:configChanges" attribute to the activity in your Manifest file. For example:

            android:label="@string/app_name" >

There's a listing of the configChanges defined here:

The next step, is to override the onConfigurationChanged() method in the activity, like this:

    public void onConfigurationChanged(Configuration newConfig) {
        Log.i(TAG, "newConfig.fontScale = " + newConfig.fontScale);


When the font size changes in the device settings, your onConfigurationChanged() method is called and an object containing the new device configuration is passed to the method, for you to handle as you please.

No comments:

Post a Comment