【问题标题】:Check orientation on Android phone在 Android 手机上检查方向
【发布时间】:2011-02-17 06:12:36
【问题描述】:

如何检查 Android 手机是横屏还是竖屏?

【问题讨论】:

标签: java android orientation


【解决方案1】:

用于确定要检索哪些资源的当前配置可从资源的Configuration 对象获得:

getResources().getConfiguration().orientation;

您可以通过查看其值来检查方向:

int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // In landscape
} else {
    // In portrait
}

更多信息可以在Android Developer找到。

【讨论】:

  • 哦,对不起,我误会了,我以为你是说如果配置发生变化,服务不会看到配置变化。您所描述的是......好吧,它什么也没看到,因为没有任何变化,因为启动器已锁定屏幕方向并且不允许它改变。所以 .orientation 没有改变是正确的,因为方向没有改变。屏幕仍然是纵向的。
  • 我能做的最接近的事情是从传感器读取方向,这涉及到我目前不太想弄清楚的数学。
  • 没什么好烦恼的。屏幕没有旋转,它仍然是纵向的,看不到任何旋转。如果您想监控用户如何移动手机而不管屏幕如何旋转,那么是的,您需要直接观察传感器,并决定如何解释您获得的有关设备移动方式的信息。
  • 如果屏幕方向是固定的,这将失败。
  • 如果活动锁定显示(android:screenOrientation="portrait"),无论用户如何旋转设备,此方法都将返回相同的值。在这种情况下,您将使用加速度计或重力传感器来正确确定方向。
【解决方案2】:

使用getResources().getConfiguration().orientation 是正确的方式。

您只需要注意不同类型的风景,设备通常使用的风景和其他。

仍然不明白如何管理。

【讨论】:

    【解决方案3】:

    这是hackbodMartijn推荐的如何获取屏幕方向的代码sn-p演示:

    ❶ 改变方向时触发:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
            int nCurrentOrientation = _getScreenOrientation();
        _doSomeThingWhenChangeOrientation(nCurrentOrientation);
    }
    

    ❷ 获取当前方向为hackbod推荐:

    private int _getScreenOrientation(){    
        return getResources().getConfiguration().orientation;
    }
    

    ❸获取当前屏幕方向有其他解决方案❷关注Martijn解决方案:

    private int _getScreenOrientation(){
            Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
            return display.getOrientation();
    }
    

    注意: 我尝试同时实现❷和❸,但在 RealDevice (NexusOne SDK 2.3) Orientation 上它返回错误的方向。

    ★所以我推荐使用解决方案 ❷ 获得屏幕方向更有优势:清晰,简单,像魅力一样工作。

    ★仔细检查方向返回以确保正确如我们预期(可能有限制取决于物理设备规格)

    希望对你有帮助,

    【讨论】:

      【解决方案4】:

      如果你在某些设备上使用 getResources().getConfiguration().orientation 你会弄错的。我们最初在http://apphance.com 中使用了这种方法。由于 Apphance 的远程日志记录,我们可以在不同的设备上看到它,并且我们看到碎片在这里发挥了作用。 我看到了奇怪的案例:例如在 HTC Desire HD 上交替使用纵向和正方形(?!):

      CONDITION[17:37:10.345] screen: rotation: 270 orientation: square
      CONDITION[17:37:12.774] screen: rotation: 0 orientation: portrait
      CONDITION[17:37:15.898] screen: rotation: 90
      CONDITION[17:37:21.451] screen: rotation: 0
      CONDITION[17:38:42.120] screen: rotation: 270 orientation: square
      

      或根本不改变方向:

      CONDITION[11:34:41.134] screen: rotation: 0
      CONDITION[11:35:04.533] screen: rotation: 90
      CONDITION[11:35:06.312] screen: rotation: 0
      CONDITION[11:35:07.938] screen: rotation: 90
      CONDITION[11:35:09.336] screen: rotation: 0
      

      另一方面,width() 和 height() 总是正确的(它被窗口管理器使用,所以最好是这样)。我想说最好的办法是始终检查宽度/高度。如果您想一想,这正是您想要的 - 知道宽度是否小于高度(纵向)、相反(横向)或它们是否相同(正方形)。

      然后归结为这个简单的代码:

      public int getScreenOrientation()
      {
          Display getOrient = 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;
      }
      

      【讨论】:

      • 谢谢!不过,初始化“方向”是多余的。
      • getWidthgetHeight 未被弃用。
      • @user3441905,是的。请改用getSize(Point outSize)。我正在使用 API 23。
      • @jarek-potiuk 它已被弃用。
      【解决方案5】:
      int ot = getResources().getConfiguration().orientation;
      switch(ot)
              {
      
              case  Configuration.ORIENTATION_LANDSCAPE:
      
                  Log.d("my orient" ,"ORIENTATION_LANDSCAPE");
              break;
              case Configuration.ORIENTATION_PORTRAIT:
                  Log.d("my orient" ,"ORIENTATION_PORTRAIT");
                  break;
      
              case Configuration.ORIENTATION_SQUARE:
                  Log.d("my orient" ,"ORIENTATION_SQUARE");
                  break;
              case Configuration.ORIENTATION_UNDEFINED:
                  Log.d("my orient" ,"ORIENTATION_UNDEFINED");
                  break;
                  default:
                  Log.d("my orient", "default val");
                  break;
              }
      

      【讨论】:

        【解决方案6】:

        还有另外一种方法:

        public int getOrientation()
        {
            if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().heightPixels)
            { 
                Toast t = Toast.makeText(this,"LANDSCAPE",Toast.LENGTH_SHORT);
                t.show();
                return 1;
            }
            else
            {
                Toast t = Toast.makeText(this,"PORTRAIT",Toast.LENGTH_SHORT);
                t.show();
                return 2;
            }       
        }
        

        【讨论】:

          【解决方案7】:

          我认为此代码在方向更改生效后可能会起作用

          Display getOrient = getWindowManager().getDefaultDisplay();
          
          int orientation = getOrient.getOrientation();
          

          如果您想在调用 setContentView 之前收到有关新方向的通知,请覆盖 Activity.onConfigurationChanged(Configuration newConfig) 函数并使用 newConfig,orientation。

          【讨论】:

            【解决方案8】:

            指定手机当前方向的完整方法:

            public String getRotation(Context context) {
                final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
                switch (rotation) {
                    case Surface.ROTATION_0:
                        return "portrait";
                    case Surface.ROTATION_90:
                        return "landscape";
                    case Surface.ROTATION_180:
                        return "reverse portrait";
                    default:
                        return "reverse landscape";
                }
            }
            

            【讨论】:

            • 您的帖子中有错字 - 应该是 .getRotation() 而不是 getOrientation
            • 为此 +1。我需要知道确切的方向,而不仅仅是横向与纵向。 getOrientation() 是正确的,除非您使用的是 SDK 8+,在这种情况下您应该使用 getRotation()。 SDK 9+ 支持“反向”模式。
            • @Keith @Paul 我不记得getOrientation() 是如何工作的,但如果使用getRotation(),这是不正确的。获取旋转"Returns the rotation of the screen from its "natural" orientation."source。因此,在手机上说 ROTATION_0 是纵向可能是正确的,但在平板电脑上,它的“自然”方向可能是横向,并且 ROTATION_0 应该返回横向而不是纵向。
            • 看起来这是加入转发的首选方法:developer.android.com/reference/android/view/…
            • 这是一个错误的答案。为什么要投票? getOrientation(float[] R, float[] values) 根据旋转矩阵计算设备的方向。
            【解决方案9】:

            Android SDK 可以很好地告诉您:

            getResources().getConfiguration().orientation
            

            【讨论】:

              【解决方案10】:

              我认为使用 getRotationv() 没有帮助,因为 http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation() 从“自然”方向返回屏幕的旋转。

              所以除非你知道“自然”方向,否则旋转是没有意义的。

              我找到了一个更简单的方法,

                Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
                Point size = new Point();
                display.getSize(size);
                int width = size.x;
                int height = size.y;
                if(width>height)
                  // its landscape
              

              请告诉我这个人是否有问题?

              【讨论】:

                【解决方案11】:

                在运行时检查屏幕方向。

                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    super.onConfigurationChanged(newConfig);
                
                    // Checks the orientation of the screen
                    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
                
                    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
                        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();        
                    }
                }
                

                【讨论】:

                  【解决方案12】:

                  解决此问题的另一种方法是不依赖于显示的正确返回值,而是依赖于 Android 资源的解析。

                  在文件夹res/values-landres/values-port中创建文件layouts.xml,内容如下:

                  res/values-land/layouts.xml:

                  <?xml version="1.0" encoding="utf-8"?>
                  <resources>
                      <bool name="is_landscape">true</bool>
                  </resources>
                  

                  res/values-port/layouts.xml:

                  <?xml version="1.0" encoding="utf-8"?>
                  <resources>
                      <bool name="is_landscape">false</bool>
                  </resources>
                  

                  在您的源代码中,您现在可以按如下方式访问当前方向:

                  context.getResources().getBoolean(R.bool.is_landscape)
                  

                  【讨论】:

                  • 我喜欢这个,因为它使用系统已经确定方向的任何方式
                  • 横向/纵向检查的最佳答案!
                  • 它在默认值文件中的值是多少?
                  【解决方案13】:

                  我知道的旧帖子。无论方向可能是或交换等。我设计了这个函数,用于将设备设置为正确的方向,而无需知道设备上的纵向和横向功能是如何组织的。

                     private void initActivityScreenOrientPortrait()
                      {
                          // Avoid screen rotations (use the manifests android:screenOrientation setting)
                          // Set this to nosensor or potrait
                  
                          // Set window fullscreen
                          this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
                  
                          DisplayMetrics metrics = new DisplayMetrics();
                          this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                  
                           // Test if it is VISUAL in portrait mode by simply checking it's size
                          boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels ); 
                  
                          if( !bIsVisualPortrait )
                          { 
                              // Swap the orientation to match the VISUAL portrait mode
                              if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
                               { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
                              else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
                          }
                          else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }
                  
                      }
                  

                  像魅力一样工作!

                  【讨论】:

                    【解决方案14】:

                    这些答案中的大部分已经发布了一段时间,其中一些使用了现在已弃用的方法和常量。

                    我已更新 Jarek's code 不再使用这些方法和常量:

                    protected int getScreenOrientation()
                    {
                        Display getOrient = getWindowManager().getDefaultDisplay();
                        Point size = new Point();
                    
                        getOrient.getSize(size);
                    
                        int orientation;
                        if (size.x < size.y)
                        {
                            orientation = Configuration.ORIENTATION_PORTRAIT;
                        }
                        else
                        {
                            orientation = Configuration.ORIENTATION_LANDSCAPE;
                        }
                        return orientation;
                    }
                    

                    请注意,不再支持Configuration.ORIENTATION_SQUARE 模式。

                    与建议使用 getResources().getConfiguration().orientation 的方法相比,我发现这在我测试过的所有设备上都是可靠的

                    【讨论】:

                    • 注意getOrient.getSize(size)需要13个api级别
                    【解决方案15】:

                    这样用,

                        int orientation = getResources().getConfiguration().orientation;
                        String Orintaion = "";
                        switch (orientation)
                        {
                            case Configuration.ORIENTATION_UNDEFINED: Orintaion = "Undefined"; break;
                            case Configuration.ORIENTATION_LANDSCAPE: Orintaion = "Landscrape"; break;
                            case Configuration.ORIENTATION_PORTRAIT:  Orintaion = "Portrait"; break;
                            default: Orintaion = "Square";break;
                        }
                    

                    在字符串中你有 Oriantion

                    【讨论】:

                      【解决方案16】:

                      有很多方法可以做到这一点,这段代码对我有用

                       if (this.getWindow().getWindowManager().getDefaultDisplay()
                                      .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                                   // portrait mode
                      } else if (this.getWindow().getWindowManager().getDefaultDisplay()
                                      .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                                            // landscape
                              }
                      

                      【讨论】:

                        【解决方案17】:

                        简单易行:)

                        1. 制作 2 个 xml 布局(即纵向和横向)
                        2. 在java文件中,写:

                          private int intOrientation;
                          

                          onCreate方法和setContentView之前写:

                          intOrientation = getResources().getConfiguration().orientation;
                          if (intOrientation == Configuration.ORIENTATION_PORTRAIT)
                              setContentView(R.layout.activity_main);
                          else
                              setContentView(R.layout.layout_land);   // I tested it and it works fine.
                          

                        【讨论】:

                          【解决方案18】:

                          我认为这个解决方案很简单

                          if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
                            user_todat_latout = true;
                          } else {
                            user_todat_latout = false;
                          }
                          

                          【讨论】:

                          • 一般来说,如果答案包含对代码的用途的解释,以及为什么在不介绍其他人的情况下解决问题的原因,答案会更有帮助。
                          • 是的,对不起,我认为如果相等 Configuration.ORIENTATION_PORTRAIT 这意味着应用程序处于纵向,则不需要准确解释这块代码检查方向 :)
                          【解决方案19】:

                          这样就覆盖了所有手机,比如 oneplus3

                          public static boolean isScreenOriatationPortrait(Context context) {
                              return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
                          }
                          

                          正确代码如下:

                          public static int getRotation(Context context) {
                              final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
                          
                              if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
                                  return Configuration.ORIENTATION_PORTRAIT;
                              }
                          
                              if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
                                  return Configuration.ORIENTATION_LANDSCAPE;
                              }
                          
                              return -1;
                          }
                          

                          【讨论】:

                            【解决方案20】:

                            同样值得注意的是,如今,如果您出于布局原因使用 getResources().getConfiguration().orientation 检查显式方向的充分理由,因为 Android 7 / API 24+ 中引入的 Multi-Window Support 可能会弄乱您的布局在任何一个方向上都相当多。最好考虑使用&lt;ConstraintLayout&gt;alternative layouts dependent on available width or height,以及确定正在使用哪种布局的其他技巧,例如某些 Fragment 是否存在附加到您的 Activity。

                            【讨论】:

                              【解决方案21】:

                              你可以使用这个(基于here):

                              public static boolean isPortrait(Activity activity) {
                                  final int currentOrientation = getCurrentOrientation(activity);
                                  return currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                              }
                              
                              public static int getCurrentOrientation(Activity activity) {
                                  //code based on https://www.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
                                  final Display display = activity.getWindowManager().getDefaultDisplay();
                                  final int rotation = display.getRotation();
                                  final Point size = new Point();
                                  display.getSize(size);
                                  int result;
                                  if (rotation == Surface.ROTATION_0
                                          || rotation == Surface.ROTATION_180) {
                                      // if rotation is 0 or 180 and width is greater than height, we have
                                      // a tablet
                                      if (size.x > size.y) {
                                          if (rotation == Surface.ROTATION_0) {
                                              result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                                          } else {
                                              result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                                          }
                                      } else {
                                          // we have a phone
                                          if (rotation == Surface.ROTATION_0) {
                                              result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                                          } else {
                                              result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                                          }
                                      }
                                  } else {
                                      // if rotation is 90 or 270 and width is greater than height, we
                                      // have a phone
                                      if (size.x > size.y) {
                                          if (rotation == Surface.ROTATION_90) {
                                              result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                                          } else {
                                              result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                                          }
                                      } else {
                                          // we have a tablet
                                          if (rotation == Surface.ROTATION_90) {
                                              result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                                          } else {
                                              result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                                          }
                                      }
                                  }
                                  return result;
                              }
                              

                              【讨论】:

                                【解决方案22】:

                                2019 年在 API 28 上进行了测试,无论用户是否设置了纵向,并且与 another, outdated answer 相比,使用最少的代码,以下提供了正确的方向:

                                /** @return The {@link Configuration#ORIENTATION_SQUARE}, {@link Configuration#ORIENTATION_PORTRAIT}, {@link Configuration#ORIENTATION_LANDSCAPE} constants based on the current phone screen pixel relations. */
                                private int getScreenOrientation()
                                {
                                    DisplayMetrics dm = context.getResources().getDisplayMetrics(); // Screen rotation effected
                                
                                    if(dm.widthPixels == dm.heightPixels)
                                        return Configuration.ORIENTATION_SQUARE;
                                    else
                                        return dm.widthPixels < dm.heightPixels ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
                                }
                                

                                【讨论】:

                                  【解决方案23】:

                                  简单的两行代码

                                  if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                                      // do something in landscape
                                  } else {
                                      //do in potrait
                                  }
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2013-01-11
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2014-03-29
                                    相关资源
                                    最近更新 更多