防止布局更改并仍然捕获 onConfigurationChanged

Prevent layout change and still catch onConfigurationChanged

我需要锁定片段的布局,以防止它在设备旋转到横向时旋转。

为此,我将其锁定在清单中:

android:screenOrientation="portrait

布局没有改变,但是当方向改变时我仍然需要做一些工作(旋转按钮)。以这种方式锁定它可以防止调用 onConfigurationChanged。

我的目标行为与默认相机应用程序完全一样。当您旋转设备时,布局保持不变,但只有按钮旋转。

有没有人能做到这一点?

您可以通过编程方式设置方向:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);

并使用此检测代码中的方向变化:

 @Override
 public void onConfigurationChanged(Configuration newConfig) {
     super.onConfigurationChanged(newConfig);
     // Do something here...
 }

如果您想以编程方式监听简单的屏幕方向变化并让您的应用程序对其做出反应,您可以使用the OrientationEventListener class来完成此操作在你的 Activity.

在 Activity 中实现方向事件处理很简单。简单地实例化一个 OrientationEventListener 并提供它的实现。例如,以下 Activity class 称为 SimpleOrientationActivity 将方向信息记录到 LogCat:

public class SimpleOrientationActivity extends Activity {
    OrientationEventListener mOrientationListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mOrientationListener = new OrientationEventListener(this,
            SensorManager.SENSOR_DELAY_NORMAL) {

            @Override
            public void onOrientationChanged(int orientation) {
                Log.v(DEBUG_TAG,
                    "Orientation changed to " + orientation);
            }
        };

       if (mOrientationListener.canDetectOrientation() == true) {
           Log.v(DEBUG_TAG, "Can detect orientation");
           mOrientationListener.enable();
       }
       else {
           Log.v(DEBUG_TAG, "Cannot detect orientation");
           mOrientationListener.disable();
       }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mOrientationListener.disable();
    }
}

如需更多帮助,请参阅 this

还有 this answer 会有所帮助。