Avoid setRequestedOrientation delay

Viewed 169

I'm experiencing a small undesired effect when trying to set the orientation of my activity:

I hace two activities: MainActivity and Activity2.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button).setOnClickListener(v -> startActivity(new Intent(this, Activity2.class)));
    }
}

public class Activity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }
}

When I click the button with the device in portrait (but displaying the MainActivity in landscape) it loads the Activity2 in portrait and takes like 1 second to rotate to landscape.

How can I avoid this and load the Activity2 with the correct orientation from the start?

Note: This is a simplified example. It is not possible to set up the orientation in the manifest since the orientation is not fixed and depends on the user input.

1 Answers

Found a way to avoid the visual effect, but it is not elegant.

By declaring

public class Activity2 extends AppCompatActivity {
   ...
}
public class Activity2Land extends Activity2 {
   ...
}

And in the manifest

    <activity
        android:name=".Activity2"
        android:screenOrientation="portrait"
        android:exported="false" />
    <activity
        android:name=".Activity2Land"
        android:screenOrientation="landscape"
        android:exported="false" />

you can workaround this issue. But, yes, you need to declare A LOT of activities if you want to support reverse and sensor orientations.

Any ideas for solving this in a correct way?

Related