How can I check if the Android phone is in Landscape or Portrait?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How can I create this custom Bottom Navigation on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
If you use getResources().getConfiguration().orientation on some devices you will get it wrong. We used that approach initially in http://apphance.com. Thanks to remote logging of Apphance we could see it on different devices and we saw that fragmentation plays its role here. I saw weird cases: for example alternating portrait and square(?!) on HTC Desire HD:
or not changing orientation at all:
On the other hand, width() and height() is always correct (it is used by window manager, so it should better be). I'd say the best idea is to do the width/height checking ALWAYS. If you think about a moment, this is exactly what you want - to know if width is smaller than height (portrait), the opposite (landscape) or if they are the same (square).
Then it comes down to this simple code:
Another way of solving this problem is by not relying on the correct return value from the display but relying on the Android resources resolving.
Create the file
layouts.xml
in the foldersres/values-land
andres/values-port
with the following content:res/values-land/layouts.xml:
res/values-port/layouts.xml:
In your source code you can now access the current orientation as follows:
Simple and easy :)
At java file, write:
at
onCreate
method and beforesetContentView
write:You can use this (based on here) :
I think this code may work after orientation change has take effect
override Activity.onConfigurationChanged(Configuration newConfig) function and use newConfig,orientation if you want to get notified about the new orientation before calling setContentView.
A fully way to specify the current orientation of the phone:
Chear Binh Nguyen