zoukankan      html  css  js  c++  java
  • 如何在 Android 程序中禁止屏幕旋转和重启Activity

    禁止屏幕随手机旋转变化

    有时候我们希望让一个程序的界面始终保持在一个方向,不随手机方向旋转而变化:
    在AndroidManifest.xml的每一个需要禁止转向的Activity配置中加入android:screenOrientation=”landscape” 属性。

    landscape = 横向
    portrait = 纵向

    避免在转屏时重启Activity

    android中每次屏幕方向切换时都会重启Activity,所以应该在Activity销毁前保存当前活动的状态,在Activity再次 Create的时候载入配置,那样,进行中的游戏就不会自动重启了!
    要避免在转屏时重启Activity,可以通过在AndroidManifest.xml文件中重新定义方向(给每个Activity加上 android:configChanges=”keyboardHidden|orientation”属性)。
    在需要控制屏幕显示方向的Activity中重写 onConfigurationChanged(Configuration newConfig)方法,这样在转屏时就不会重启Activity了。

    if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) {
        //横向
        setContentView(R.layout.file_list_landscape);
    } else {
        //竖向
        setContentView(R.layout.file_list);
    }
    <activity android:name="com.myapp.MyActivity"
              android:label="@string/app_name"
              android:screenOrientation="landscape"
              android:configChanges="orientation"
              >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    android:screenOrientation=”landscape”
    android:configChanges=”keyboardHidden|orientation”

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
     
        if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) {
            //横向
            setContentView(R.layout.file_list_landscape);
        } else {
            //竖向
            setContentView(R.layout.file_list);
        }
    }

    在模拟器中可以按 CTL+F11 模拟做屏幕旋转。

    参考:

    How to disable Screen Auto-Rotation on Android
    http://digitaldumptruck.jotabout.com/?p=897

    如何在 Android 程序中禁止屏幕旋转和重启Activity
    http://www.androidcn.com/news/20110302/00001299.html

  • 相关阅读:
    模板模式变形
    理解volatitle带来的可见性
    数据库隔离级别
    Spring对POST内容进行处理的坑
    动态加载JS和CSS
    MySQL性能优化总结
    JS自执行匿名函数
    CDATA为何物?
    如何编写高效的jQuery代码
    war和war exploded区别
  • 原文地址:https://www.cnblogs.com/bluestorm/p/3665890.html
Copyright © 2011-2022 走看看