1

現在の画面の向きはデフォルトで縦に設定されているため、SensorEventListener を実装してデバイスの画面の向きを検出したいと考えています。私のレイアウトには、レイアウトとは独立して回転する必要があるボタンがいくつか含まれており、これを行う唯一の方法は (私が知っている限り) onConfigurationChanged をオーバーライドし、対応するアニメーションを各画面の向きに追加することであるため、これを行う必要があります。設定された向きが縦に固定されているため、 OrientationEventListener は機能しないと思います。では、センサー自体から画面の向きや角度の回転を取得するにはどうすればよいでしょうか?

4

1 に答える 1

3

OrientationEventListener は、向きが固定されていても機能します。https://stackoverflow.com/a/8260007/1382108を参照してください。ドキュメントに従ってセンサーを監視します。次の定数を定義するとします。

private static final int THRESHOLD = 40;
public static final int PORTRAIT = 0;
public static final int LANDSCAPE = 270;
public static final int REVERSE_PORTRAIT = 180;
public static final int REVERSE_LANDSCAPE = 90;
private int lastRotatedTo = 0;

数値は OrientationEventListener が返すものに対応するため、自然なランドスケープ デバイス (タブレット) を使用している場合は、それを考慮する必要があります。Android でデバイスの自然な (デフォルト) 方向を確認する方法 (つまり、モトローラ チャームやフリップアウト) .

 @Override
public void onOrientationChanged(int orientation) {
    int newRotateTo = lastRotatedTo;
    if(orientation >= 360 + PORTRAIT - THRESHOLD && orientation < 360 ||
            orientation >= 0 && orientation <= PORTRAIT + THRESHOLD)
        newRotateTo = 0;
    else if(orientation >= LANDSCAPE - THRESHOLD && orientation <= LANDSCAPE + THRESHOLD)
        newRotateTo = 90;
    else if(orientation >= REVERSE_PORTRAIT - THRESHOLD && orientation <= REVERSE_PORTRAIT + THRESHOLD)
        newRotateTo = 180;
    else if(orientation >= REVERSE_LANDSCAPE - THRESHOLD && orientation <= REVERSE_LANDSCAPE + THRESHOLD)
        newRotateTo = -90;
    if(newRotateTo != lastRotatedTo) {
        rotateButtons(lastRotatedTo, newRotateTo);
        lastRotatedTo = newRotateTo;
    }
}

次のようなrotateButtons関数:

public void rotateButtons(int from, int to) {

    int buttons[] = {R.id.buttonA, R.id.buttonB};
    for(int i = 0; i < buttons.length; i++) {
        RotateAnimation rotateAnimation = new RotateAnimation(from, to, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        rotateAnimation.setDuration(200);
        rotateAnimation.setFillAfter(true);
        View v = findViewById(buttons[i]);
        if(v != null) {
            v.startAnimation(rotateAnimation);
        }
    }
}
于 2015-10-23T09:49:46.370 に答える