在Android上禁用运行时的屏幕旋转

pen*_*ang 3 android

public class testScreenRotation extends Activity {
/** Called when the activity is first created. */

private int mRuntimeOrientation;
   private boolean mDisableScreenRotation=true;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mRuntimeOrientation = this.getScreenOrientation();
    setContentView(R.layout.main);


}
protected int getScreenOrientation() {
/*
    Display display = getWindowManager().getDefaultDisplay();
    int orientation = display.getOrientation();

    if (orientation == Configuration.ORIENTATION_UNDEFINED) {
       orientation = getResources().getConfiguration().orientation;

       if (orientation == Configuration.ORIENTATION_UNDEFINED) {
          if (display.getWidth() == display.getHeight())
             orientation = Configuration.ORIENTATION_SQUARE;
          else if(display.getWidth() < display.getHeight())

             orientation = Configuration.ORIENTATION_PORTRAIT;
          else
             orientation = Configuration.ORIENTATION_LANDSCAPE;
          }
       }


    return orientation;
  */
    return Configuration.ORIENTATION_PORTRAIT;
 }
@Override
public void onConfigurationChanged(Configuration newConfig) {
    // TODO Auto-generated method stub
       if (mDisableScreenRotation) {
             super.onConfigurationChanged(newConfig);
             this.setRequestedOrientation(mRuntimeOrientation);
          } else {
             mRuntimeOrientation = this.getScreenOrientation();
             super.onConfigurationChanged(newConfig);
          }
       }

}
Run Code Online (Sandbox Code Playgroud)

我的应用程序如上所述,并在xml中添加android:configChanges ="orientation".当我的应用程序启动我的屏幕是PORTRAIT时,我按ctrl + F12,屏幕也是roate,屏幕是LANDSCAPE,第二个我按ctrl + F12,屏幕也在旋转,屏幕是PORTRAIT,然后按ctrl + F12,屏幕保持PORTRAIT.所以我再次按,屏幕保持肖像.我的问题是,当应用程序启动时,为什么我的屏幕不能保持PORTRAIT.

编辑:我想使用代码来控制屏幕roate,如果我能做到这一点?

pec*_*a85 15

如果您尝试让应用程序始终处于纵向模式,则可以将此行添加到清单中的元素

android:screenOrientation="portrait"
Run Code Online (Sandbox Code Playgroud)

在AndroidManifest.xml文件的每个活动中添加此行.


zen*_*hoy 7

我相信你正在寻找的方法是 Activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_<PORTRAIT/LANDSCAPE>)

这一起

android:configChanges="orientation"

对于清单中的那个活动告诉系统你将自己处理方向应禁用自动重定向.