Android:检测方向已更改
我需要检测应用程序中的方向变化,但我不希望我的布局从纵向更改为横向。 目前我正在使用 OrientationEventListener,但是检测方向角度还不够。我想检测用户从纵向变为横向,反之亦然,而这不仅仅是检测方向角是 90 度还是 270 度。
我想做与 Android 相同的检测来改变 Activity 的方向。我尝试覆盖 onConfigurationChanged
并检查方向是否为横向/纵向,但这仍然会将我的活动布局更改为横向。
有没有办法使用 onConfigurationChanged 但强制布局保持纵向?
是否有另一种方法可以在不使用 OrientationEventListener
的情况下检测方向变化。最终我可以实现我自己的方向改变算法,对此有什么想法吗?它必须比 if(90-THRESHOLD <=orientation <= 90+THRESHOLD) 更复杂,我想检测用户是否进行了完整的移动纵向->横向或横向->肖像。
感谢您的帮助,
菲利佩
I need to detect an orientation change in my application, but I don't want my layout to be changed from portrait to landscape.
Currently I'm using the OrientationEventListener
however detecting the orientation angle is not enough. I want to detect that the user changed from portrait to landscape or viceversa, and that is not just detecting if the orientation angle is 90 or 270.
I want to do the same detection that the Android does to change the activity's orientantion. I tried overriding onConfigurationChanged
and check if orientantion is landscape/portrait, however this still changes my activity layout to landscape.
Is there a way to use onConfigurationChanged but force the layout to stay in portrait?
Is there another way to detect orientantion change without using OrientationEventListener
. Ultimately I can implement my own orientation changed algorithm, any ideas on this? It has to be something more complex than if(90-THRESHOLD <= orientation <= 90+THRESHOLD)
, I want to detect if the user made the complete movement Portrait->Landscape or Landscape->Portrait.
Thanks for the help,
Filipe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,在尝试使用 Android API 但无法完成我需要的操作后,我实现了自己的算法,实际上并没有那么复杂:
我使用了 OrientationEventListener,并计算方向是否位于 4 个方向点(在我的代码中,我仅检测
LANDSCAPE_RIGHT
和PORTRAIT_UP
:Ok, after trying to use the Android API and not being able to do what I need, I implemented my own algorithm and actually it wasn't that complicated:
I used a OrientationEventListener, and calculated if the orientation is in the 4 orientation points (in my code I only detect
LANDSCAPE_RIGHT
andPORTRAIT_UP
:嗨,尖叫声是您要找的吗?
Hi screamingnoises is this what you`re looking for?
我创建了以下类来检测方向变化,保持我的活动原始方向:
按如下方式使用它:
在 AndroidManifest.xml 中 -
在您的活动中:
I created the following class to detect orientation changes, keeping my activity original orientation:
Use it as follows:
In AndroidManifest.xml -
In your activity:
Asaf Pinhassi 答案的 kotlin 版本。
A kotlin version of the Asaf Pinhassi answer.
为了检测方向,我们将要求 Activity 向我们提供 Activity 的宽度和高度,这样我们就可以判断 Width > 是否为 Width > 。高度将是“横向”或相反高度>宽度为“肖像”-以下代码经过测试并且可以工作。
To detect orientation, we will ask the activity to provide us with width and height of the activity, so we can find if Width > Height which will be "Landscape" or the opposite Height > width which is "Portrait" - The Following Code is tested and Working.