les*_*hka 3 android android-layout android-orientation
我正在开发一个只支持两个方向的应用程序,纵向和反向肖像,所以我sensorPortrait在我的清单中写了" ",它运行良好.
问题是,我想为这两个方向使用不同的布局.
启用sensorPortrait禁用" onConfigurationChange"呼叫.
我用:
orientationEventListener = new OrientationEventListener(this) {
@Override
public void onOrientationChanged(int i) {
int newOrientation = getScreenOrientation();
if (newOrientation != orientation) {
orientation = newOrientation;
if (newOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
...
setContentView(R.layout.main);
} else if (newOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
...
setContentView(R.layout.main_reverse_portrait);
}
}
}
};
orientationEventListener.enable();
Run Code Online (Sandbox Code Playgroud)
问题是这个代码在更改方向后被调用,因此当用户首先旋转手机时,他们会看到之前的布局,由Android自动旋转,然后是正确的布局.看起来不可接受,你知道怎么解决吗?
我建议你使用configChanges和覆盖onConfigurationChanged(Configuration newConfig)方法.如果方向不是您支持的方向,请忽略方向.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
...
setContentView(R.layout.main);
} else if (newOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
...
setContentView(R.layout.main_reverse_portrait);
}
}
Run Code Online (Sandbox Code Playgroud)
这个答案可能会进一步帮助您.
getChangingConfigurations()您可以使用一种方法onStop()来确定导致活动被销毁的配置更改.在这种情况下,您不需要使用onConfigurationChanged()回调.
sensorPortrait手动使用和检查旋转角度onCreate.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Display display = ((WindowManager)
context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if (rotation == Surface.ROTATION_180) { // reverse portrait
setContentView(R.layout.main_reverse_portrait);
} else { // for all other orientations
setContentView(R.layout.main);
}
...
}
Run Code Online (Sandbox Code Playgroud)