int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
// In landscape
} else {
// In portrait
}
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
intOrientation = getResources().getConfiguration().orientation;
if (intOrientation == Configuration.ORIENTATION_PORTRAIT)
setContentView(R.layout.activity_main);
else
setContentView(R.layout.layout_land); // I tested it and it works fine.
同样值得注意的是,如今,如果你是出于布局原因而使用getResources().getConfiguration().orientation检查显式方向,那么就没有那么好的理由了,因为在Android 7 / API 24+中引入的支持多窗口可能会在任何一个方向上打乱你的布局。最好考虑使用<ConstraintLayout>和可选择的布局取决于可用的宽度或高度,以及其他确定使用哪种布局的技巧,例如是否存在某些片段附加到您的活动。
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;
}