how to detect orientation of android device?

2019-01-04 10:08发布

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.

6条回答
2楼-- · 2019-01-04 10:43

You just need to know the height and the width of your canvas... your surface... your monitor... etc.

maybe you can get it with :

if (canvas.getHeight()>canvas.getWidth() ) {
//portrait
}
else
{
//landscape
}
查看更多
欢心
3楼-- · 2019-01-04 10:52

There is a nice article about this subject which is a have-to-read: One Screen Turn Deserves Another

查看更多
来,给爷笑一个
4楼-- · 2019-01-04 10:52

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.

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
查看更多
成全新的幸福
5楼-- · 2019-01-04 10:56

You can also use:

getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
查看更多
成全新的幸福
6楼-- · 2019-01-04 10:59

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:

if(mViewpager.getTag().equals("portrait"))
  // is in portrait
else
  // is in landscape
查看更多
聊天终结者
7楼-- · 2019-01-04 11:07

Use the getRotation method:

Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();

From the documentation:

Returns the rotation of the screen from its "natural" orientation. The returned value may be Surface.ROTATION_0 (no rotation), Surface.ROTATION_90, Surface.ROTATION_180, or Surface.ROTATION_270. For example, if a device has a naturally tall screen, and the user has turned it on its side to go into a landscape orientation, the value returned here may be either Surface.ROTATION_90 or Surface.ROTATION_270 depending on the direction it was turned. The angle is the rotation of the drawn graphics on the screen, which is the opposite direction of the physical rotation of the device. For example, if the device is rotated 90 degrees counter-clockwise, to compensate rendering will be rotated by 90 degrees clockwise and thus the returned value here will be Surface.ROTATION_90.

Keep in mind that getRotation was introduced from Android 2.2. Use getOrientation if your target are older devices.

查看更多
登录 后发表回答