本文介绍了Android的确定屏幕方向运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个伪code检测屏幕旋转活动,并决定保留或改变屏幕方向。

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

我如何做类似的事情在Android的?

How do I make similar things in Android?

编辑:实际上,我在寻找的答案在在哪里处理方向改变。我不想加入screenOrientation =肖像,以固定取向。

I'm actually looking answer on Where to handle orientation changes. I do not want to fix the orientation by adding screenOrientation="portrait".

我需要的东西,类似于onConfigurationChanges(),在那里我可以处理的方向,但我无需手动重绘的视图。

I need something, similar to onConfigurationChanges(), where I can handle the orientation, but do no need me to manually redraw the view.

推荐答案

您需要一个显示实例首先:

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.

更新

好吧,让我们说你的 oAllow VAR是布尔键,默认值为

Okay, let's say you've an oAllow var which is Boolean and default value is 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.

更新

getOrientation()已去precated的。相反,使用 getRotation()。要检查设备是在横向模式下,你可以做这样的事情:

getOrientation() is already deprecated see here. Instead Use 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            
}

这篇关于Android的确定屏幕方向运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 04:29