Switch activiy on orientation changed?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 03:53:18

问题


How can I switch to another activity when rotating the phone?

My requirements:

  • Activity A and B are portrait only
  • Acitvity L is landscape only
  • When landscape mode of A or B would be displayed, L is started instead. When portrait of L would be displayed, A or B are displayed.

I can create this behaviour, expect for the back button. When it is pressed I'm either getting A/B in landscape or L in portrait, which I want to prevent.

What I'm doing (Activities A & B, but L is similar)

To trigger the activity call on orientation change:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    int newOrientation = newConfig.orientation;
    if (newOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        Intent intent = new Intent(this, ActivityL.class);
        startActivity(intent);
    }

    super.onConfigurationChanged(newConfig);
}

I want something like the following. But manually (re)setting the orientation prevents onConfigurationChanged() from being called at all:

@Override
public void onResume(){
    super.onResume();

    int currentOrientation = this.getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

On course the same happens if I do it in other lifecycle methods or onCreate(...).

All activities have:

  android:screenOrientation="sensor"

I also tried imitating the orientation change using the rotationg angle, but then the behavior seems mostly random and not even close to the normal orientation change.


回答1:


I suppose setRequestedOrientation() overrides what I had defined in the AndroidManifest:

android:screenOrientation="sensor"

I need to reset it to sensor to get the automated orientation changes back:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    int newOrientation = newConfig.orientation;
    if (newOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        Intent intent = new Intent(this, ActivityL.class);
        startActivity(intent);
    }
    super.onConfigurationChanged(newConfig);

    // Reset to sensor:
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}

I'm a bit surprised that calling it within onConfigurationChanged(..) works, since that method is no longer called by orientation changes. But I guess the configuration is changed in some other way when the activity is resumed(when back button is pressed).



来源:https://stackoverflow.com/questions/58554769/switch-activiy-on-orientation-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!