如何检查 Android 手机是横向还是纵向?
用于确定要检索哪些资源的当前配置可从 Resources 的 Configuration
对象获得:
getResources().getConfiguration().orientation;
您可以通过查看其值来检查方向:
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
// In landscape
} else {
// In portrait
}
更多信息可在 Android Developer 中找到。
如果你在某些设备上使用 getResources().getConfiguration().orientation,你会弄错。我们最初在 http://apphance.com 中使用了这种方法。由于 Apphance 的远程日志记录,我们可以在不同的设备上看到它,并且我们看到碎片在这里发挥了作用。我看到了奇怪的案例:例如在 HTC Desire HD 上交替使用纵向和正方形(?!):
CONDITION[17:37:10.345] screen: rotation: 270 orientation: square
CONDITION[17:37:12.774] screen: rotation: 0 orientation: portrait
CONDITION[17:37:15.898] screen: rotation: 90
CONDITION[17:37:21.451] screen: rotation: 0
CONDITION[17:38:42.120] screen: rotation: 270 orientation: square
或根本不改变方向:
CONDITION[11:34:41.134] screen: rotation: 0
CONDITION[11:35:04.533] screen: rotation: 90
CONDITION[11:35:06.312] screen: rotation: 0
CONDITION[11:35:07.938] screen: rotation: 90
CONDITION[11:35:09.336] screen: rotation: 0
另一方面,width() 和 height() 总是正确的(它被窗口管理器使用,所以应该更好)。我想说最好的办法是始终检查宽度/高度。如果您考虑一下,这正是您想要的 - 知道宽度是否小于高度(纵向)、相反(横向)或它们是否相同(正方形)。
然后归结为这个简单的代码:
public int getScreenOrientation()
{
Display getOrient = getWindowManager().getDefaultDisplay();
int orientation = Configuration.ORIENTATION_UNDEFINED;
if(getOrient.getWidth()==getOrient.getHeight()){
orientation = Configuration.ORIENTATION_SQUARE;
} else{
if(getOrient.getWidth() < getOrient.getHeight()){
orientation = Configuration.ORIENTATION_PORTRAIT;
}else {
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
return orientation;
}
getWidth
和 getHeight
未被弃用。
getSize(Point outSize)
。我正在使用 API 23。
解决此问题的另一种方法是不依赖于显示的正确返回值,而是依赖于 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>
资源/值端口/layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">false</bool>
</resources>
在您的源代码中,您现在可以按如下方式访问当前方向:
context.getResources().getBoolean(R.bool.is_landscape)
指定手机当前方向的完整方法:
public String getRotation(Context context) {
final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
switch (rotation) {
case Surface.ROTATION_0:
return "portrait";
case Surface.ROTATION_90:
return "landscape";
case Surface.ROTATION_180:
return "reverse portrait";
default:
return "reverse landscape";
}
}
getOrientation()
是如何工作的,但如果使用 getRotation()
,这是不正确的。获取轮换 "Returns the rotation of the screen from its "natural" orientation."
source。因此,在手机上说 ROTATION_0 是纵向可能是正确的,但在平板电脑上,它的“自然”方向可能是横向,而 ROTATION_0 应该返回横向而不是纵向。
以下是 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)方向上它返回错误的方向。
★所以我推荐使用解决方案❷来获得屏幕方向,这样更有优势:清晰,简单,像魅力一样工作。
★仔细检查方向返回以确保正确如我们预期(可能有限制取决于物理设备规格)
希望有帮助,
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;
}
自从大多数这些答案已经发布并且有些使用现在已弃用的方法和常量以来已经过去了一段时间。
我已更新 Jarek's code 以不再使用这些方法和常量:
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;
}
请注意,模式 Configuration.ORIENTATION_SQUARE
不再受支持。
与建议使用 getResources().getConfiguration().orientation
的方法相比,我发现这在我测试过的所有设备上都是可靠的
使用 getResources().getConfiguration().orientation
是正确的方法。
您只需要注意不同类型的景观、设备通常使用的景观和其他景观。
仍然不明白如何管理它。
在运行时检查屏幕方向。
@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();
}
}
还有另一种方法:
public int getOrientation()
{
if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().heightPixels)
{
Toast t = Toast.makeText(this,"LANDSCAPE",Toast.LENGTH_SHORT);
t.show();
return 1;
}
else
{
Toast t = Toast.makeText(this,"PORTRAIT",Toast.LENGTH_SHORT);
t.show();
return 2;
}
}
Android SDK 可以很好地告诉你:
getResources().getConfiguration().orientation
2019 年在 API 28 上进行了测试,无论用户是否设置了纵向,并且与 another, outdated answer 相比,使用最少的代码,以下提供了正确的方向:
/** @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;
}
这样就覆盖了所有手机,例如 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
}
我认为此代码在方向更改生效后可能会起作用
Display getOrient = getWindowManager().getDefaultDisplay();
int orientation = getOrient.getOrientation();
重写 Activity.onConfigurationChanged(Configuration newConfig) 函数并使用 newConfig,orientation 如果您想在调用 setContentView 之前获得有关新方向的通知。
我认为使用 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
请告诉我这个人是否有问题?
我知道的旧帖子。无论方向可能是或交换等。我设计了此功能,用于将设备设置为正确的方向,而无需知道设备上的纵向和横向功能是如何组织的。
private void initActivityScreenOrientPortrait()
{
// Avoid screen rotations (use the manifests android:screenOrientation setting)
// Set this to nosensor or potrait
// Set window fullscreen
this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
DisplayMetrics metrics = new DisplayMetrics();
this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Test if it is VISUAL in portrait mode by simply checking it's size
boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels );
if( !bIsVisualPortrait )
{
// Swap the orientation to match the VISUAL portrait mode
if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
{ this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
}
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }
}
奇迹般有效!
使用这种方式,
int orientation = getResources().getConfiguration().orientation;
String Orintaion = "";
switch (orientation)
{
case Configuration.ORIENTATION_UNDEFINED: Orintaion = "Undefined"; break;
case Configuration.ORIENTATION_LANDSCAPE: Orintaion = "Landscrape"; break;
case Configuration.ORIENTATION_PORTRAIT: Orintaion = "Portrait"; break;
default: Orintaion = "Square";break;
}
在字符串中你有 Oriantion
有很多方法可以做到这一点,这段代码对我有用
if (this.getWindow().getWindowManager().getDefaultDisplay()
.getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
// portrait mode
} else if (this.getWindow().getWindowManager().getDefaultDisplay()
.getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
// landscape
}
简单易行:)
制作 2 个 xml 布局(即 Portrait 和 Landscape) 在 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); // 我测试了它,它工作正常。
我认为这个解决方案很简单
if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
user_todat_latout = true;
} else {
user_todat_latout = false;
}
还值得注意的是,如今,如果您出于布局原因使用 getResources().getConfiguration().orientation
检查显式方向,则没有充分的理由,因为 Android 7 / API 24+ 中引入的 Multi-Window Support 可能会严重影响您的布局在任一方向。最好考虑使用 <ConstraintLayout>
和 alternative layouts dependent on available width or height,以及确定正在使用哪种布局的其他技巧,例如是否存在某些 Fragment 附加到您的 Activity。
您可以使用它(基于 here):
public static boolean isPortrait(Activity activity) {
final int currentOrientation = getCurrentOrientation(activity);
return currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
public static int getCurrentOrientation(Activity activity) {
//code based on https://www.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
final Display display = activity.getWindowManager().getDefaultDisplay();
final int rotation = display.getRotation();
final Point size = new Point();
display.getSize(size);
int result;
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) {
// if rotation is 0 or 180 and width is greater than height, we have
// a tablet
if (size.x > size.y) {
if (rotation == Surface.ROTATION_0) {
result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else {
result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
}
} else {
// we have a phone
if (rotation == Surface.ROTATION_0) {
result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
} else {
result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
}
} else {
// if rotation is 90 or 270 and width is greater than height, we
// have a phone
if (size.x > size.y) {
if (rotation == Surface.ROTATION_90) {
result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else {
result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
}
} else {
// we have a tablet
if (rotation == Surface.ROTATION_90) {
result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
} else {
result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
}
}
return result;
}
android:screenOrientation="portrait"
),无论用户如何旋转设备,此方法都将返回相同的值。在这种情况下,您将使用加速度计或重力传感器来正确确定方向。