gpt4 book ai didi

android - setRequestedOrientation,但仍根据传感器改变

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:11:35 27 4
gpt4 key购买 nike

我想在处理屏幕方向方面模拟 youtube 视频观看行为。

用例:
p1。当用户按下最大化时 -> Activity 总是进入横向
p2。当用户按下最小化时 -> Activity 总是进入纵向
p3。当用户旋转设备时 -> 即使之前应用了 p1p2,屏幕方向也应相应改变。

目前我使用:

 @Override
public void onClick(View view) {
if (getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}

然而,这会永久锁定方向,并且 p3 失败。

最佳答案

经过一段时间的尝试,我找到了正确的解决方案。首先 - 问题是 android 在调用 setRequestedOrientation 后锁定屏幕,你不能混合使用两者,唯一的办法就是手动完成所有操作。

方法如下:

class PlayerOrientationListener extends OrientationEventListener {
PlayerOrientationListener() {
super(VideoPlayerActivity.this);
}

@Override
public void onOrientationChanged(int orientation) {
int threshold = 5;
if (Math.abs(orientation - 0) < threshold) orientation = 0;
else if (Math.abs(orientation - 90) < threshold) orientation = 90;
else if (Math.abs(orientation - 180) < threshold) orientation = 180;
else if (Math.abs(orientation - 270) < threshold) orientation = 270;

switch (orientation) {
case 0:
if (!orientationLandscapeLocked) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
orientationPortraitLocked = false;
}
break;
case 90:
if (!orientationPortraitLocked) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
orientationLandscapeLocked = false;
}
break;
case 180:
if (!orientationLandscapeLocked) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
orientationPortraitLocked = false;
}
break;
case 270:
if (!orientationPortraitLocked) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
orientationLandscapeLocked = false;
}
break;
}
}
}

和 Activity 代码:

View.OnClickListener onExpandClick = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
orientationLandscapeLocked = true;
orientationPortraitLocked = false;
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
orientationPortraitLocked = true;
orientationLandscapeLocked = false;
}
}
};
btnExpandVideo.setOnClickListener(onExpandClick);

orientationListener = new PlayerOrientationListener();
orientationListener.enable();

关于android - setRequestedOrientation,但仍根据传感器改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46953691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com