Android How to - Log Screen Orientation Changes








The following code finds out what happens to an activity's state when the device changes orientation.

Example

The following demonstrates the behavior of an activity when the device changes orientation.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<EditText
    android:id="@+id/txtField1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
//from   w  ww. java  2s.  co m
public class MainActivity extends Activity {
    @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     Log.d("StateInfo", "onCreate");
 }

 @Override
 public void onStart() {
     Log.d("StateInfo", "onStart");
     super.onStart();
 }

 @Override
 public void onResume() {
     Log.d("StateInfo", "onResume");
     super.onResume();
 }

 @Override
 public void onPause() {
     Log.d("StateInfo", "onPause");
     super.onPause();
 }

 @Override
 public void onStop() {
     Log.d("StateInfo", "onStop");
     super.onStop();
 }

 @Override
 public void onDestroy() {
     Log.d("StateInfo", "onDestroy");
     super.onDestroy();
 }

 @Override
 public void onRestart() {
     Log.d("StateInfo", "onRestart");
     super.onRestart();
 }
}
null




Note

You need to ensure that you take the necessary steps to preserve the state of your activity before it changes orientation.

For any activity, you should save whatever state you need to save in the onPause() method, which is fired every time the activity changes orientation.

Important

Only views that are named via the android:id attribute in an activity will have their state persisted when the activity they are contained in is destroyed.

For example, the user may change orientation while entering some text into an EditText view. Any text inside the EditText view will be persisted and restored automatically. If you do not name the EditText view using the android:id attribute, the activity will not be able to persist the text currently contained within it.