如何查看Android手机是横屏还是竖屏?
当前回答
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.
其他回答
我认为这段代码可以在方向改变生效后工作
Display getOrient = getWindowManager().getDefaultDisplay();
int orientation = getOrient.getOrientation();
覆盖的活动。onConfigurationChanged(Configuration newConfig)函数,如果你想在调用setContentView之前得到关于新方向的通知,请使用newConfig,orientation。
解决这个问题的另一种方法是不依赖于显示的正确返回值,而是依赖于Android资源的解析。
在res/values-land和res/values-port文件夹中创建文件layouts.xml,内容如下:
res / values-land / layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">true</bool>
</resources>
res / values-port / layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">false</bool>
</resources>
在你的源代码中,你现在可以访问当前方向,如下所示:
context.getResources().getBoolean(R.bool.is_landscape)
这样就覆盖了所有的手机,如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;
}
只是简单的两行代码
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// do something in landscape
} else {
//do in potrait
}
在运行时检查屏幕方向。
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
推荐文章
- 如何分割逗号分隔的字符串?
- Java字符串—查看字符串是否只包含数字而不包含字母
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- Mockito.any()传递带有泛型的接口
- 在IntelliJ 10.5中运行测试时,出现“NoSuchMethodError: org.hamcrest. matcher . descripbemismatch”
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 使用String.split()和多个分隔符
- Java数组有最大大小吗?
- 在Android中将字符串转换为Uri
- 从JSON生成Java类?
- 为什么java.util.Set没有get(int index)?
- Swing和AWT的区别是什么?
- 如何在NestedScrollView内使用RecyclerView ?
- 为什么Java流是一次性的?
- 移动到另一个EditText时,软键盘下一步点击Android