Search This Blog

Support my cause by downloading

Saturday, 18 May 2013

Android Screen Rotation : handling Activity Runtime orientation change

Handling orientation change in android is bit interesting topic to explore. on change of orientation your Android device's width changes to height and vice versa. It make developer to force some changes in layout for better user expeperience. We can handle user interface while changing orientation using two way. Lets discuss best possible way to handle activity orientation change.

1) Avoid recreating activity using android:configChanges="orientation|screenSize" and android:screenOrientation="user". Its not easy to save state all the process running and resuming them. It may force you write lots of code. If Application structure is complex and User Interface is similar in all orientation then using this way is prodigy. Even thought this way give you event of changing orientation in onConfigurationChanged(Configuration newConfig), but it add overhead to change layouts.

Tip1 : try to minimize the padding and margin to minimize the impact of screen size.
Tip 2: Use Relative Layout

Pros : Avoiding huge among of code if process are in enough numberCons : Using this way in multipane layout is not possible. Its shows the bad user experience.


2) Handle recreating activity and assign fresh resource on base of orientation. Attribute android:screenOrientation="user" force activity to recreating to load the new resource on the base of current screen orientation. Remove android:configChanges="orientation|screenSize" in this case
Tip 1: Create two layout folder inside resource layout for portrait and layout-land for landscape
Tip 2: Android provide a way to save current activity state while changing application orientation. Save your data inside onSaveInstanceState(Bundle outState);


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("progress", 10);
        outState.putBoolean("isRecreated", true);
        super.onSaveInstanceState(outState);
    }

Tip 3: Now check in onCreate(Bundle savedInstanceState), is it creating or recreating. Restore the process and thread in case recreating

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int progress = 0;
        boolean isRecreated = false;
        if (savedInstanceState != null) {
            // Restore Process and Thread
            progress = savedInstanceState.getInt("progress");
            isRecreated = savedInstanceState.getBoolean("isRecreated");
        } else {
            // Start Fresh Process and Thread
        }

        Log.e(String.valueOf(progress), String.valueOf(isRecreated));
    }

Pros : Code Overhead
Cons : Better user exeperience. easy to handle Multipane layout

Android News and source code