本文翻译自:Check orientation on Android phone
如何检查Android手机是横向还是纵向?
#1楼
参考:https://stackoom.com/question/BjK5/检查Android手机的方向
#2楼
A fully way to specify the current orientation of the phone: 一种指定手机当前方向的完整方式:
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";
}
}
Chear Binh Nguyen Chear Binh Nguyen
#3楼
Android SDK可以告诉你这个很好:
getResources().getConfiguration().orientation
#4楼
i think using getRotationv() doesn't help because http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation() Returns the rotation of the screen from its "natural" orientation. 我认为使用getRotationv()没有帮助,因为http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation()从“自然”返回屏幕的旋转取向。
so unless you know the "natural" orientation, rotation is meaningless. 因此,除非你知道“自然”方向,否则轮换是毫无意义的。
i found an easier way, 我找到了一种更简单的方法
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
please tell me if there is a problem with this someone? 请告诉我这个人是否有问题?
#5楼
Check screen orientation in runtime. 在运行时检查屏幕方向。
@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();
}
}
#6楼
Another way of solving this problem is by not relying on the correct return value from the display but relying on the Android resources resolving. 解决此问题的另一种方法是不依赖于显示器的正确返回值,而是依赖于Android资源解析。
Create the file layouts.xml
in the folders res/values-land
and res/values-port
with the following content: 使用以下内容在文件夹res/values-land
和res/values-port
创建文件layouts.xml
:
res/values-land/layouts.xml: RES /价值观土地/ layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">true</bool>
</resources>
res/values-port/layouts.xml: RES /值端口/ layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">false</bool>
</resources>
In your source code you can now access the current orientation as follows: 在源代码中,您现在可以按如下方式访问当前方向:
context.getResources().getBoolean(R.bool.is_landscape)