- 论坛徽章:
- 0
|
By default, when screen orientation is changed, Activity will destructed and recreated, if you want to store some state before it is destructed, and restored it after it is recreated, you can overload functions onSaveInstanceState and onRestoreInstanceState of Activity as following:
public void onSaveInstanceState(Bundle outState)
{
//---store whatever you need to persist—
outState.putString("MyPrivateID", "1234567890");
super.onSaveInstanceState(outState);
}
When an Activity is recreated, the onCreate event is fired first, followed by the onRestoreInstanceState event:
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 destructed 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 class Activity, 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
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/9577/showart_1853549.html |
|