By default, when screen orientation is changed, Activities will destroyed and recreated. If you want to store some state before it is destroyed and restored it after it is recreated, you can overload functions onSaveInstanceState and onRestoreInstanceState of Activity subclass to implement those feature as following:
public void onSaveInstanceState(Bundle outState)
{
//---store whatever you need to persist—
outState.putString("MyPrivateID", "1234567890");
super.onSaveInstanceState(outState);
}
public void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
//---retrieve the information persisted earlier---
String strPrivateID = savedInstanceState.getString("MyPrivateID");
}
Via one of following information, we can prevent Activity to be destroyed and recreated when screen orientation is changed:
1) Declare fixed screen orientation in manifest:
android:screenOrientation="sensor"
android:label="@string/app_name">
the value of android:screenOrientation can be: portrait, landscape, sensor(Automatically adjust)
2) Declare to bypass Activity Destruction
android:configChanges="keyboardHidden|orientation"
android:label="@string/app_name">
If you need to get notification when screen orientation is changed, you can overload the function onConfigurationChanged of Activity subclass, or register an orientation listener (Define a class which extends OrientationListener, instance that class in Activity.onCreate, and call function enable() of the defined orientation listener class), i.e.
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.xxxx); //Set new content view
/*
If you used theme in manifest, it is impossible to change to other theme except in onCreate(), so if the used theme contains background images, it will be stretched when screen orientation is changed, but you can change them (background image) by calling getWindow().setBackgroundDrawableResource(R.drawable.xxxxxx);
*/
}
More information, please refer to online document:
Title: "Developing Orientation-Aware Android Applications"
Address: http://www.devx.com/wireless/Article/40792/1954
阅读(1943) | 评论(0) | 转发(0) |