冻结屏幕方向屏幕、方向

2023-09-07 16:01:56 作者:紫陌未央,笔触琉璃

有复选框与以下code:

There is CheckBox with following code:

    CheckBox cb = (CheckBox)findViewById(R.id.freezer);
    cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
            }
        }
    });

所以,当我检查了,屏幕旋转到系统默认的方向(横向对我的平板电脑)。

So, when i check it, screen is rotated to default system orientation (landscape for my tablet).

我需要冻结当前方向。如果你转向装置纵向和切换复选框,设备旋转必须ingored直到复选框被选中。

I need to freeze CURRENT orientation. If you turned device to portrait and toggled CheckBox, device rotation must be ingored until CheckBox is unchecked.

Display.getRotation()不是一个解决方案,因为每个设备有它自己的Surface.ROTATION

Display.getRotation() is not a solution, because each device has it's own Surface.ROTATION

推荐答案

所以,这里是我的解决方案。

So, here is my solution.

private int getCurentOrientation() {
    Display d = ((WindowManager) getSystemService(WINDOW_SERVICE))
            .getDefaultDisplay();
    boolean isWide = d.getWidth() >= d.getHeight();
    switch (d.getRotation()) {
    case Surface.ROTATION_0:
        return isWide ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    case Surface.ROTATION_90:
        return isWide ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
    case Surface.ROTATION_180:
        return isWide ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
    case Surface.ROTATION_270:
        return isWide ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }
    return -1;
}

private void lockOrientation(boolean lock) {
    if (lock) {
        setRequestedOrientation(getCurentOrientation());
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
    }
}

在4设备(2智能手机和2片),它可以作为nedded。

On 4 devices (2 smartphones and 2 tablets) it works as nedded.