Android 屏幕旋转

来源:互联网 发布:外贸搜客户软件怎么样 编辑:程序博客网 时间:2024/04/29 03:44
上文已经说过屏幕旋转时的Activity的生命周期。
当数据量较大时,在屏幕旋转时,一般都采用两种方式避免Activity从新布局。
第一种:设置ScreenOrientation属性,通过属性设置可以避免在旋转时出现从新布局的情况:

 如果不想让软件在横竖屏之间切换,最简单的办法就是在项目的 AndroidManifest.xml中找到你所指定的Activity中加上android:screenOrientation属性,他有以下几个参数:

"unspecified"

默认值由系统来判断显示方向.判定的策略是和设备相关的,所以不同的设备会有不同的显示方向. 
"landscape" 
      横屏显示(宽比高要长) 
"portrait" 
       竖屏显示(高比宽要长) 
"user" 
       用户当前首选的方向 
"behind" 
       和该Activity下面的那个Activity的方向一致(在Activity堆栈中的) 
"sensor" 
        有物理的感应器来决定。如果用户旋转设备这屏幕会横竖屏切换。 
"nosensor" 
         忽略物理感应器,这样就不会随着用户旋转设备而更改了 ( "unspecified"设置除外 )。

如:

 <activity
            android:label="@string/app_name"
            android:name=".ActivityLifeTestActivity"
            android:screenOrientation="landscape" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

同样也可以在应用程序中使用 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)方法来控制屏幕的方向。

通过该种方法,Activity的生命周期依然正常,当前的Activty依然会被killed然后从新建立。

 

第二种:配置 android:configChanges属性

 如果不需要从新载入,可以在androidmanifest.xml中加入配置 android:configChanges="orientation",配置android:configChanges的作用就是如文档所说的:Specify one or more configuration changes that the activity will handle itself. If not specified, the activity will be restarted if any of these configuration changes happen in the system。这样在程序中. Activity就不会重复的调用onCreate()甚至不会调用onPause.onResume.只会调用一个 onConfigurationChanged(Configuration newConfig)。

 如果我在android:configChanges中只设置orientation,他依然会重新加载,只有设置了 orientation|keyboardHidden它才会只调用一个onConfigurationChanged(Configuration newConfig)

如果需要重新载入,则不需要做任何修改。不过如果需要在重新载入过程中保存之前的操作内容或数据,则需要保存之前的数据。然后在activity的 onCreate()中取出来。当然,如此就不能设置android:configChanges()了,否则就不会调用onCreate()方法。 

      没有设置android:configChanges,切换屏幕时会是onPause,onStop,onDestroy,然后onCreate,onStart,onResume,也就是先停掉,然后再从onCreate开始

 

设置android:configChanges后,只进入

@Override
public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.i(TAG, "横屏");
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.i(TAG, "竖屏");
        }

 }

 

通过上诉两种方法,基本上完成了屏幕切换时所需要的知识 


原创粉丝点击