简体   繁体   English

Android在运行时确定屏幕方向

[英]Android determine screen orientation at runtime

Here's a pseudo code to detect screen rotate event, and decide to retain or changes the screen orientation. 这是一个用于检测屏幕旋转事件的伪代码,并决定保留或更改屏幕方向。

public boolean onOrientationChanges(orientation) {
  if(orientation == landscape)
    if(settings.get("lock_orientation"))
      return false;   // Retain portrait mode
    else
      return true; // change to landscape mode

  return true; 
}

How do I make similar things in Android? 如何在Android中制作类似的内容?

EDIT: I'm actually looking answer on Where to handle orientation changes . 编辑:我实际上正在寻找答案在哪里处理方向变化 I do not want to fix the orientation by adding screenOrientation="portrait". 我不想通过添加screenOrientation =“portrait”来修复方向。

I need something, similar to onConfigurationChanges(), where I can handle the orientation, but do no need me to manually redraw the view. 我需要一些东西,类似于onConfigurationChanges(),我可以处理方向,但不需要我手动重绘视图。

You need a Display instance firstly: 首先需要一个Display实例:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();

Then orientation may be called like this: 然后可以像这样调用方向:

int orientation = display.getOrientation();

Check orientation as your way and use this to change orientation : 检查方向,并使用它来改变方向

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

I hope it helps. 我希望它有所帮助。

Update : 更新

Okay, let's say you've an oAllow var which is Boolean and default value is False . 好吧,假设你有一个oAllow var,它是Boolean ,默认值是False

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
    int orientation = display.getOrientation(); 
    switch(orientation) {
        case Configuration.ORIENTATION_PORTRAIT:
            if(!oAllow) {
                    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            break;
        case Configuration.ORIENTATION_LANDSCAPE:
            if(!oAllow) {
                    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            break;
    }
}

You can add more choices. 您可以添加更多选择。

I didn't try this sample, but at least tells you some clues about how to solve. 我没有尝试这个样本,但至少告诉你一些关于如何解决的线索。 Tell me if you got any error. 如果您有任何错误,请告诉我。

UPDATE UPDATE

getOrientation() is already deprecated see here . getOrientation()已被弃用, 请参见此处 Instead Use getRotation() . 而是使用getRotation() To check if the device is in landscape mode you can do something like this: 要检查设备是否处于横向模式,您可以执行以下操作:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
        .getDefaultDisplay();

int orientation = display.getRotation();

if (orientation == Surface.ROTATION_90
        || orientation == Surface.ROTATION_270) {
    // TODO: add logic for landscape mode here            
}

Try running 试试跑步

getResources().getConfiguration().orientation

From your context object to figure out what is the screen orientation at runtime, the possible values are documented here 从您的上下文对象中确定运行时的屏幕方向, 这里记录了可能的值

In order to catch the orientation change event you can find the answer in the Android Dev Guide: Handling the Configuration Change Yourself 为了捕捉方向更改事件,您可以在Android开发指南中找到答案: 处理配置更改自己

From the guide : 从指南:

For example, the following manifest code declares an activity that handles both the screen orientation change and keyboard availability change: 例如,以下清单代码声明了一个处理屏幕方向更改和键盘可用性更改的活动:

<activity android:name=".MyActivity" <activity android:name =“。MyActivity”
android:configChanges="orientation|keyboardHidden" 机器人:configChanges = “方向| keyboardHidden”
android:label="@string/app_name"> 机器人:标签= “@串/ APP_NAME”>

Now, when one of these configurations change, MyActivity does not restart. 现在,当其中一个配置发生更改时,MyActivity不会重新启动。 Instead, the MyActivity receives a call to onConfigurationChanged(). 相反,MyActivity接收对onConfigurationChanged()的调用。 This method is passed a Configuration object that specifies the new device configuration. 此方法传递一个Configuration对象,该对象指定新设备配置。 By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. 通过读取“配置”中的字段,您可以确定新配置并通过更新界面中使用的资源进行适当的更改。 At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity. 在调用此方法时,将更新活动的Resources对象以根据新配置返回资源,这样您就可以轻松重置UI的元素,而无需系统重新启动您的活动。

... ...

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

You don't need to intercept the event and then override it. 您不需要拦截事件然后覆盖它。 Just use: 只需使用:

// Allow rotation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
// Lock rotation (to Landscape)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);

Points to note here are, if on Jellybean and above this will allow a 180 degree rotation when locked. 这里要注意的是,如果在Jellybean及以上,这将允许在锁定时旋转180度。 Also when unlocked this only allows rotation if the user's master settings is to allow rotation. 此外,当解锁时,如果用户的主设置允许旋转,则仅允许旋转。 You can forbid 180 degree rotations and override the master settings and allow rotation, and much much more, so check out the options in ActivityInfo 您可以禁止180度旋转并覆盖主设置并允许旋转等等,因此请查看ActivityInfo中的选项

In addition, if you have pre-set that there is to be no rotation, then your activity will not be destroyed and then restarted, just for you to set the orientation back which will again cause the activity to be restarted; 此外,如果您已经预先设置了没有旋转,那么您的活动将不会被销毁然后重新启动,只是为了您将方向设置回来,这将再次导致活动重新启动; Thus setting what you want in advance can be much more efficient . 因此,提前设置您想要的内容可以更加高效

Pre Jellybean use ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE -- no 180 degree rotation with this. Pre Jellybean使用ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE - 没有180度旋转。

Check your android screen orientation at Runtime: 在运行时检查您的Android屏幕方向:

ListView listView = (ListView) findViewById(R.id.listView1);
if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
    //do work for landscape screen mode.
    listView.setPadding(0, 5, 0, 1);
} else if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
    //Do work for portrait screen mode.
    listView.setPadding(1, 10, 1, 10);
}

Another solution to determine screen orientation: 确定屏幕方向的另一种解决方案

public boolean isLandscape() {
    return Resources.getSystem().getDisplayMetrics().widthPixels - Resources.getSystem().getDisplayMetrics().heightPixels > 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM