如何查看Android手机是横屏还是竖屏?
当前回答
我认为这个解决方法很简单
if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
user_todat_latout = true;
} else {
user_todat_latout = false;
}
其他回答
2019年在API 28上测试,无论用户是否设置了纵向方向,与另一个过时的答案相比,使用最少的代码,以下代码提供了正确的方向:
/** @return The {@link Configuration#ORIENTATION_SQUARE}, {@link Configuration#ORIENTATION_PORTRAIT}, {@link Configuration#ORIENTATION_LANDSCAPE} constants based on the current phone screen pixel relations. */
private int getScreenOrientation()
{
DisplayMetrics dm = context.getResources().getDisplayMetrics(); // Screen rotation effected
if(dm.widthPixels == dm.heightPixels)
return Configuration.ORIENTATION_SQUARE;
else
return dm.widthPixels < dm.heightPixels ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
}
大多数答案已经发布了一段时间,其中一些使用了现在已弃用的方法和常量。
我已经更新了Jarek的代码,不再使用这些方法和常量:
protected int getScreenOrientation()
{
Display getOrient = getWindowManager().getDefaultDisplay();
Point size = new Point();
getOrient.getSize(size);
int orientation;
if (size.x < size.y)
{
orientation = Configuration.ORIENTATION_PORTRAIT;
}
else
{
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
return orientation;
}
注意配置模式。不再支持ORIENTATION_SQUARE。
与建议使用getResources().getConfiguration().orientation的方法相比,我发现这个方法在我测试过的所有设备上都是可靠的
Android SDK可以很好地告诉你:
getResources().getConfiguration().orientation
这样就覆盖了所有的手机,如oneplus3
public static boolean isScreenOrientationPortrait(Context context) {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}
正确代码如下:
public static int getRotation(Context context) {
final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
return Configuration.ORIENTATION_PORTRAIT;
}
if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
return Configuration.ORIENTATION_LANDSCAPE;
}
return -1;
}
我认为使用getRotationv()没有帮助,因为 http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation()返回屏幕从其“自然”方向的旋转。
所以除非你知道“自然”方向,旋转是没有意义的。
我找到了一个更简单的方法
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
if(width>height)
// its landscape
请告诉我这个人有什么问题吗?
推荐文章
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 使用Enum实现单例(Java)
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何设置整个应用程序在纵向模式?
- 如何在Java中按两个字段排序?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?