我怎样才能获得当前的屏幕方向?

我只想设置一些标志,当我的方向是横向的,所以当onCreate()中重新创build活动时,我可以在纵向和横向之间切换。 我已经有一个布局土地XML处理我的布局。

public void onConfigurationChanged(Configuration _newConfig) { if (_newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { this.loadURLData = false; } if (_newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { this.loadURLData = true; } super.onConfigurationChanged(_newConfig); } 

覆盖onConfigurationChanged将阻止我的layout-land xml以横向加载。

我只想在onCreate()中获取设备的当前方向。 我怎样才能得到这个?

 Activity.getResources().getConfiguration().orientation 
 int orientation = this.getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) { //code for portrait mode } else { //code for landscape mode } 

当这个超类是Activity

在一些设备void onConfigurationChanged()可能会崩溃。 用户将使用此代码获取当前的屏幕方向。

 public int getScreenOrientation() { Display getOrient = getActivity().getWindowManager().getDefaultDisplay(); int orientation = Configuration.ORIENTATION_UNDEFINED; if(getOrient.getWidth()==getOrient.getHeight()){ orientation = Configuration.ORIENTATION_SQUARE; } else{ if(getOrient.getWidth() < getOrient.getHeight()){ orientation = Configuration.ORIENTATION_PORTRAIT; }else { orientation = Configuration.ORIENTATION_LANDSCAPE; } } return orientation; } 

并使用

 if (orientation==1) // 1 for Configuration.ORIENTATION_PORTRAIT { // 2 for Configuration.ORIENTATION_LANDSCAPE //your code // 0 for Configuration.ORIENTATION_SQUARE } 
 int rotation = getWindowManager().getDefaultDisplay().getRotation(); 

这将给所有的方向,如正常和反向

并像处理它

 int angle = 0; switch (rotation) { case Surface.ROTATION_90: angle = -90; break; case Surface.ROTATION_180: angle = 180; break; case Surface.ROTATION_270: angle = 90; break; default: angle = 0; break; } 
 getActivity().getResources().getConfiguration().orientation 

此命令为纵向返回int值1,为横向返回2

如果有人想获得有意义的方向描述(就像那些用reverseLandscapesensorLandscape等传递给onConfigurationChanged(..) ),只需使用getRequestedOrientation()

在你的活动课上使用下面的方法:

  @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Checks the orientation of the screen if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { setlogo();// Your Method Log.d("Daiya", "ORIENTATION_LANDSCAPE"); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { setlogoForLandScape();// Your Method Log.d("Daiya", "ORIENTATION_PORTRAIT"); } } 

然后为了声明你的活动处理了一个configuration改变,在你的清单文件中编辑适当的元素,以包含android:configChanges属性值,该值代表你想要处理的configuration。 android:configChanges属性的文档中列出了可能的值(最常用的值是“orientation”,以防止在屏幕方向更改时重新启动,“keyboardHidden”防止键盘可用性更改时重新启动)。 您可以通过使用pipe道将它们分开来在属性中声明多个configuration值 字符。

 <activity android:name=".MyActivity" android:configChanges="orientation|keyboardHidden" android:label="@string/app_name"> 

就这样!!

如果你想覆盖onConfigurationChanged方法,并仍然想要做的基本的东西,然后考虑使用super.onConfigyrationChanged()作为第一个语句在重写方法。