如何查看Android手机是横屏还是竖屏?
当前回答
只是简单的两行代码
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// do something in landscape
} else {
//do in potrait
}
其他回答
int ot = getResources().getConfiguration().orientation;
switch(ot)
{
case Configuration.ORIENTATION_LANDSCAPE:
Log.d("my orient" ,"ORIENTATION_LANDSCAPE");
break;
case Configuration.ORIENTATION_PORTRAIT:
Log.d("my orient" ,"ORIENTATION_PORTRAIT");
break;
case Configuration.ORIENTATION_SQUARE:
Log.d("my orient" ,"ORIENTATION_SQUARE");
break;
case Configuration.ORIENTATION_UNDEFINED:
Log.d("my orient" ,"ORIENTATION_UNDEFINED");
break;
default:
Log.d("my orient", "default val");
break;
}
下面是hackbod和Martijn推荐的如何获得屏幕方向的代码片段演示:
改变时触发
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int nCurrentOrientation = _getScreenOrientation();
_doSomeThingWhenChangeOrientation(nCurrentOrientation);
}
将当前方向设置为hackbod
private int _getScreenOrientation(){
return getResources().getConfiguration().orientation;
}
还有其他方法可以获得当前屏幕方向,参照Martijn方案:
private int _getScreenOrientation(){
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
return display.getOrientation();
}
★注意: 我试过这两种实现,但在RealDevice (NexusOne SDK 2.3) Orientation上,它返回了错误的方向。
★所以我推荐使用解决方案来获得屏幕定位,有更多的优势:清楚,简单,工作就像一个魅力。
★仔细检查方向回归,以确保符合我们的预期(可能有限制取决于物理设备规格)
希望能有所帮助,
It's also worth noting that nowadays, there's less good reason to check for explicit orientation with getResources().getConfiguration().orientation if you're doing so for layout reasons, as Multi-Window Support introduced in Android 7 / API 24+ could mess with your layouts quite a bit in either orientation. Better to consider using <ConstraintLayout>, and alternative layouts dependent on available width or height, along with other tricks for determining which layout is being used, e.g. the presence or not of certain Fragments being attached to your Activity.
使用getresource () .getConfiguration()。方向是正确的。
你只需要注意不同类型的景观,设备通常使用的景观和其他的。
还是不知道该怎么处理。
简单易行:)
制作2个xml布局(即纵向和横向) 在java文件中,写入: private int intOrientation; 在onCreate方法和setContentView之前写入: intOrientation = getResources().getConfiguration().orientation; if (intOrientation == Configuration.ORIENTATION_PORTRAIT) setContentView (R.layout.activity_main); 其他的 setContentView (R.layout.layout_land);//我测试了它,它工作正常。
推荐文章
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 使用Enum实现单例(Java)
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何设置整个应用程序在纵向模式?
- 如何在Java中按两个字段排序?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 文件之间的差异。路径中的分隔符和斜杠