Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2108689
  • 博文数量: 413
  • 博客积分: 10926
  • 博客等级: 上将
  • 技术积分: 3862
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-09 18:14
文章分类

全部博文(413)

文章存档

2015年(5)

2014年(1)

2013年(5)

2012年(6)

2011年(138)

2010年(85)

2009年(42)

2008年(46)

2007年(26)

2006年(59)

分类: Java

2009-03-06 12:59:18

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) |
给主人留下些什么吧!~~