So sperren Sie die Ausrichtung zur Laufzeit


107

Gibt es eine Möglichkeit, die Ausrichtung zur Laufzeit zu sperren? Zum Beispiel möchte ich dem Benutzer erlauben, den Bildschirm für Querformat zu sperren, wenn sich der Benutzer gerade im Querformat befindet, und die Menüoption umschalten.

Antworten:


133
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

Wird eine Aktivität aufgerufen, wird sie für die Landschaft gesperrt. Suchen Sie nach den anderen Flags in der ActivityInfo-Klasse. Sie können es wieder im Hochformat sperren oder es sensor- / schiebereglergesteuert machen.

Weitere Informationen hier: http://www.devx.com/wireless/Article/40792


13
OK danke. Das funktioniert super. Das wird die aktuelle Orientierung bekommen. getResources (). getConfiguration (). Orientierung
Jared

7
Vorsichtig! Sie müssen unterscheiden, was getConfiguration () zurückgibt und was setRequestedOrientation will - siehe meine Antwort unten für Details
Andy Weinstein

Bei diesem Ansatz gibt es ein Problem. Stellen Sie sicher, dass Sie den Kommentar dieser Antwort
Bugs Happen

aber es legt die gleiche Ausrichtung für alle Aktivitäten fest, gibt es eine andere Möglichkeit, die Ausrichtung zu ändern
silverFoxA

106

Achten Sie auf den Unterschied zwischen dem, was getConfiguration zurückgibt, und dem, was setRequestedOrientation wünscht - beide sind int, stammen jedoch aus unterschiedlichen konstanten Definitionen.

Hier erfahren Sie, wie Sie die aktuelle Ausrichtung sperren und dabei 180-Grad-Flips zulassen

int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
else {
   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}

13
Möglicherweise bevorzugen Sie die Verwendung von SCREEN_ORIENTATION_USER_LANDSCAPE, da dies keine 180-Grad-Umkehrungen zulässt, wenn der Benutzer die Bildschirmdrehung in den Einstellungen deaktiviert hat. In ähnlicher Weise ist SCREEN_ORIENTATION_USER beim Zurückschalten auf freie Rotation besser als SCREEN_ORIENTATION_SENSOR, da letzteres freie Rotation ermöglicht, selbst wenn die Einstellungen dies nicht zulassen.
Steve Waring

Brillant! Wenn Sie zur umgekehrten Ausrichtung wechseln, muss keine Neukonfiguration durchgeführt werden. Zumindest auf Geräten, auf denen ich es getestet habe. Es ist wirklich wichtig zu wissen, ob Sie die Neukonfiguration während einiger
Dialogshows

47

Dies funktioniert auf Geräten mit umgekehrtem Hoch- und Querformat.

Schloss Orientierung:

    int orientation = getActivity().getRequestedOrientation();
    int rotation = ((WindowManager) getActivity().getSystemService(
            Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
    switch (rotation) {
    case Surface.ROTATION_0:
        orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        break;
    case Surface.ROTATION_90:
        orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        break;
    case Surface.ROTATION_180:
        orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
        break;
    default:
        orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
        break;
    }

    getActivity().setRequestedOrientation(orientation);

Orientierung freischalten:

   getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

5
Rotationsquelle "Returns the rotation of the screen from its "natural" orientation." abrufen . Auf einem Telefon, auf dem ROTATION_0 als Hochformat angezeigt wird, ist dies wahrscheinlich korrekt. Auf einem Tablet ist die "natürliche" Ausrichtung jedoch wahrscheinlich Querformat, und ROTATION_0 sollte Querformat anstelle von Hochformat zurückgeben.
jp36

@ jp36, ich habe auf einem Nexus 7 getestet, das eine natürliche Ausrichtung hat, die der eines Telefons entspricht. Vielen Dank für den Test auf einem größeren Tablet (das ich nicht habe).
Pstoppani

1
Wie jp36 sagte, funktioniert es nicht auf Tablets mit natürlicher Landschaftsorientierung!
DominicM

Wie testen wir das umgekehrte Porträt im Gerät?
AndyBoy

27

Ich schien einen ähnlichen Fall gehabt zu haben. Ich wollte jede Ausrichtung unterstützen, musste aber nach einem bestimmten Punkt im Workflow in der aktuellen Ausrichtung bleiben. Meine Lösung war:

Beim Eintritt in den geschützten Workflow:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

Beim Beenden des geschützten Workflows:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

2
Dies gilt nicht für den OQ, zumindest unter Android> = 16. setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) setzt das Gerät möglicherweise auch im Hochformat auf Querformat, während sich die Frage auf die angegebene Sperrausrichtung bezieht.
Greg7gkb

3
Wenn ich es auf Nosensor setze, kehre ich in den Hochformat zurück, wenn ich mich im Querformat befand. Stattdessen habe ich SCREEN_ORIENTATION_LOCKED verwendet und es hat bei mir
funktioniert

1
@JiMMaR SCREEN_ORIENTATION_LOCKED ist der beste Weg für Android> = 18. Wenn Sie jedoch auf etwas Niedrigeres abzielen, funktioniert dies nicht. Ich schlage vor, die Antwort von jp36 unten zu verwenden.
Patrick Boos

23

Alternative zur @ pstoppani-Antwort mit Unterstützung für Tablets (Wie bei der @ pstoppani-Antwort funktioniert dies nur auf Geräten> 2.2)
-Test auf Samsung Galaxy SIIIundSamsung Galaxy Tab 10.1

public static void lockOrientation(Activity activity) {
    Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    int rotation = display.getRotation();
    int tempOrientation = activity.getResources().getConfiguration().orientation;
    int orientation = 0;
    switch(tempOrientation)
    {
    case Configuration.ORIENTATION_LANDSCAPE:
        if(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90)
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        else
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
        break;
    case Configuration.ORIENTATION_PORTRAIT:
        if(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270)
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        else
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
    }
    activity.setRequestedOrientation(orientation);
}

Danke, es funktioniert gut , aber ich verstand nicht, warum es Prüfung mit ||in rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90und mit rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270. Also ich habe 2 Zweifel :::: erstens, warum ROTATION_0statt ROTATION_180im zweiten Fall und ein anderes warum 0 Grad mit 90 nicht 180 prüfen ??
AndyBoy

@AndyBoy hat es mit der Standardausrichtung von Geräten zu tun. Normalerweise haben Telefone eine Standardausrichtung im Hochformat, was bedeutet, dass die Drehung für Hochformat Null zurückgibt. Einige Tablets haben jedoch eine Standardeinstellung für Querformat, was bedeutet, dass die Drehung für Querformat Null zurückgibt. Die verschiedenen ||Überprüfungen behandeln also die beiden möglichen Standardausrichtungen basierend auf der Berichtslandschaft des Geräts im Vergleich zum Hochformat.
jp36

5

Hier ist mein Code, Sie könnten mit einer dieser Methoden Ihren Bildschirm sperren und nach Abschluss der Aufgabe ihn mit entsperren entsperren:

/** Static methods related to device orientation. */
public class OrientationUtils {
    private OrientationUtils() {}

    /** Locks the device window in landscape mode. */
    public static void lockOrientationLandscape(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /** Locks the device window in portrait mode. */
    public static void lockOrientationPortrait(Activity activity) {
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /** Locks the device window in actual screen mode. */
    public static void lockOrientation(Activity activity) {
        final int orientation = activity.getResources().getConfiguration().orientation;
        final int rotation = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();

        // Copied from Android docs, since we don't have these values in Froyo 2.2
        int SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8;
        int SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9;

        // Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO
        if (!BuildVersionUtils.hasGingerbread()) {
            SCREEN_ORIENTATION_REVERSE_LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            SCREEN_ORIENTATION_REVERSE_PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        }

        if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90){
            if (orientation == Configuration.ORIENTATION_PORTRAIT){
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            else if (orientation == Configuration.ORIENTATION_LANDSCAPE){
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        }
        else if (rotation == Surface.ROTATION_180 || rotation == Surface.ROTATION_270) 
        {
            if (orientation == Configuration.ORIENTATION_PORTRAIT){
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_PORTRAIT);
            }
            else if (orientation == Configuration.ORIENTATION_LANDSCAPE){
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }
        }
    }

    /** Unlocks the device window in user defined screen mode. */
    public static void unlockOrientation(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
    }

}

0

Hier ist die Xamarin-Konvertierung der obigen Antwort von @pstoppani.

HINWEIS: Dies ist für ein Fragment, ersetzen Sie Aktivität. mit diesem. wenn innerhalb einer Aktivität verwendet.

public void LockRotation()
{
    ScreenOrientation orientation;

    var surfaceOrientation = Activity.WindowManager.DefaultDisplay.Rotation;

    switch (surfaceOrientation) {
        case SurfaceOrientation.Rotation0:
            orientation = ScreenOrientation.Portrait;
            break;
        case SurfaceOrientation.Rotation90:
            orientation = ScreenOrientation.Landscape;
            break;
        case SurfaceOrientation.Rotation180:
            orientation = ScreenOrientation.ReversePortrait;
            break;
        default:
            orientation = ScreenOrientation.ReverseLandscape;
            break;
    }

    Activity.RequestedOrientation = orientation;
}

public void UnlockRotation()
{
    Activity.RequestedOrientation = ScreenOrientation.Unspecified;
}

Dies ist nicht getestet, da es vor der Verwendung mit einem anderen Ansatz durchgeführt wurde, kann jedoch von Nutzen sein.


Dies ist die gleiche Antwort wie bei pstoppani und schlägt auf einem Tablet fehl.
Tim Autin
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.