如何检测Android设备的方向?
是否可以简单地检测 Android 设备的当前方向,而无需编写侦听器并处理位置矩阵? 在我的应用程序中,我现在只想知道当前方向 - 垂直或水平。但是我不想听轴测事件或其他事件。
Is it possible simple to detect current orientation of android device, without programming a listener and handling the position matrix?
In my app I want only to know current orientation - vertical or horizontal - at the moment. However I don't want to listen to events of axiometry or other events.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您还可以使用:
You can also use:
使用
getRotation
方法:文档:
请记住,
getRotation
是从 Android 2.2 引入的。如果您的目标是较旧的设备,请使用getOrientation
。Use the
getRotation
method:From the documentation:
Keep in mind that
getRotation
was introduced from Android 2.2. UsegetOrientation
if your target are older devices.我认为最安全、最简单的方法是在 XML 中为活动的某些元素添加标签。例如,在纵向布局中将viewpager的标签设置为“portrait”,在横向布局中将其设置为“landscape”。然后在 oncreate 中检查该标签,如下所示:
I think the safest and easiest way is to add a tag for some element of your activity in XML. For example, set the viewpager's tag to "portrait" in the portrait layout and set it to "landscape" in in landscape. Then in your oncreate check for that tag like so:
您只需要知道画布的高度和宽度...您的表面...您的显示器...等。
也许您可以通过以下方式获得:
You just need to know the height and the width of your canvas... your surface... your monitor... etc.
maybe you can get it with :
您可以从上面的代码中创建一个扩展函数:
在您的资源目录中创建一个包含以下内容的
constants.xml
文件:然后您的代码就像(例如,Recyclerview 的垂直/水平布局)一样简单一个片段:
You could make an extension function from the code above:
In your resource directory create a
constants.xml
file with the following contents:You code is then as easy as (e.g. vertical / horizontal layout for a Recyclerview in a Fragment:
这可能不相关,但如果您偶然需要知道这一点,因为您想将设备锁定到其当前方向,您可以在以下两行代码之间切换。
This may not be relevant, but if by chance you need to know this because you want to lock the device into its’ current orientation you can toggle between the following two lines of code.