一般在视频开发中,涉及到播放器横竖屏的转换时,无需要考虑到横竖屏切花 activity的生命周期如何保证切换时activity不会被重建,则需要执行以下操作:</pre><pre name="code" class="java">横竖屏切换时禁止调用生命周期的方法:在清单文件中给activity配置这个属性: 让原来的界面自己适应屏幕横竖切换,不是先销毁再运行一个新的竖屏
android:configChanges="keyboardHidden|screenSize|orientation"
固定屏幕的方向:
android:screenOrientation="landscape" //landscape横屏,portrait竖屏,sensor自动感应,可以横竖屏自适应;
<!--配置configChanges这个属性: 让原来的界面自己适应屏幕横竖切换,不是先销毁再运行一个新的竖屏
横竖屏切换时禁止调用生命周期的方法在清单文件中给activity配置configChanges这个属性
固定屏幕的方向:
android:screenOrientation="landscape"
常见参数: landscape横屏,portrait竖屏,sensor自动感应,可以横竖屏自适应
-->
<activity
android:configChanges="keyboardHidden|screenSize|orientation"
android:name="com.example.hsqp.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
当然,也可以使用代码进行设置:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
1. 如果要让软件在横竖屏之间切换,由于横竖屏的高宽会发生转换,有可能会要求不同的布局。可以通过以下方法来切换布局:
1)在res目录下建立layout-land和layout-port目录,相应的layout文件不变,比如main.xml。layout-land是横屏的layout,layout-port是竖屏的layout,其他的不用管,模拟器会自动寻找。
2)通过 this.getResources().getConfiguration().orientation来判断当前是横屏还是竖屏然后来加载相应的 xml布局文件。因为当屏幕变为横屏的时候,系统会重新呼叫当前Activity的onCreate方法,你可以把以下方法放在你的onCreate中来检查当前的方向,然后可以让你的setContentView来载入不同的layout xml.if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
Log.i("info", "landscape"); // 横屏
}
else if (this.getResources().getConfiguration().orientation ==Configuration.ORIENTATION_PORTRAIT) {
Log.i("info", "portrait"); // 竖屏
}
2.重新载入问题。如果不需要从新载入,可以在AndroidManifest.xml中加入配置 android:configChanges="orientation|keyboardHidden",配置 android:configChanges的作用就是如文档所说的:Specify one or more configuration changesthat
the activity will handle itself. If not specified, the activity will berestarted if any of these configuration changes happen in the system。这样在程序中Activity就不会重复的调用onCreate()甚至不会调用onPause、onResume.只会调用一个 onConfigurationChanged(Configuration newConfig)。如果需要重新载入,则不需要做任何修改。不过如果需要在重新载入过程中保存之前的操作内容或数据,则需要保存之前的数据。然后在
activity的onCreate()中取出来。当然,如此就不能设置android:configChanges()了,否则就不会调用 onCreate()方法。
如果要彻底禁止翻转,可以设置android:screenOrientation的属性为nosensor,如此就可以忽略重力感应带来的麻烦了。不过在模拟器上不管用,在真机上是正确的。android:screenOrientation="portrait"
则无论手机如何变动,拥有这个属性的activity都将是竖屏显示。
android:screenOrientation="landscape",为横屏显示。
568

被折叠的 条评论
为什么被折叠?



