ChatGPT解决这个技术问题 Extra ChatGPT

在 Android 手机上检查方向

如何检查 Android 手机是横向还是纵向?

在类似的线程上查看此答案:stackoverflow.com/a/26601009/3072449
为什么不只是添加一个 Kotlin 标签,以便在使用 Kotlin 关键字的搜索时更容易找到
@Magic Hands Pellegrin:这个问题不相关。如果您删除您的评论,我们(我们这些浪费时间去看另一个线程的人)将不胜感激。

A
AlexS

用于确定要检索哪些资源的当前配置可从 Resources 的 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"),无论用户如何旋转设备,此方法都将返回相同的值。在这种情况下,您将使用加速度计或重力传感器来正确确定方向。
P
Paŭlo Ebermann

如果你在某些设备上使用 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 它已被弃用。
P
Paul

解决此问题的另一种方法是不依赖于显示的正确返回值,而是依赖于 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>

资源/值端口/layouts.xml:

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

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

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

我喜欢这个,因为它使用系统已经确定方向的任何方式
它在默认值文件中的值是多少?
E
Emma

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

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) 根据旋转矩阵计算设备的方向。
C
Community

以下是 hackbodMartijn 推荐的如何获取屏幕方向的代码片段演示:

❶ 改变方向时触发:

@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)方向上它返回错误的方向。

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

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

希望有帮助,


T
Taryn
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;
        }

C
Community

自从大多数这些答案已经发布并且有些使用现在已弃用的方法和常量以来已经过去了一段时间。

我已更新 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 级别
s
skwear

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

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

仍然不明白如何管理它。


K
Kumar

在运行时检查屏幕方向。

@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();        
    }
}

M
Michael Dillon

还有另一种方法:

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;
    }       
}

P
Peter Lang

Android SDK 可以很好地告诉你:

getResources().getConfiguration().orientation

M
ManuelTS

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;
}

s
shb

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

public static boolean isScreenOrientationPortrait(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;
}

R
Rezaul Karim

只需简单的两行代码

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

D
Daniel

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

Display getOrient = getWindowManager().getDefaultDisplay();

int orientation = getOrient.getOrientation();

重写 Activity.onConfigurationChanged(Configuration newConfig) 函数并使用 newConfig,orientation 如果您想在调用 setContentView 之前获得有关新方向的通知。


s
steveh

我认为使用 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

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


C
Codebeat

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

   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); }

    }

奇迹般有效!


佚名

使用这种方式,

    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


M
Mehroz Munir

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

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

3
3 revs, 3 users 65%

简单易行:)

制作 2 个 xml 布局(即 Portrait 和 Landscape) 在 java 文件中,写入: private int intOrientation;在 onCreate 方法和 setContentView 之前写: intOrientation = getResources().getConfiguration().orientation; if (intOrientation == Configuration.ORIENTATION_PORTRAIT) setContentView(R.layout.activity_main);否则 setContentView(R.layout.layout_land); // 我测试了它,它工作正常。


T
Tom Aranda

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

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

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

还值得注意的是,如今,如果您出于布局原因使用 getResources().getConfiguration().orientation 检查显式方向,则没有充分的理由,因为 Android 7 / API 24+ 中引入的 Multi-Window Support 可能会严重影响您的布局在任一方向。最好考虑使用 <ConstraintLayout>alternative layouts dependent on available width or height,以及确定正在使用哪种布局的其他技巧,例如是否存在某些 Fragment 附加到您的 Activity。


a
android developer

您可以使用它(基于 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;
}