1

我想通過實現SensorEventListener來檢測設備的屏幕方向,因爲它的當前屏幕方向默認設置爲縱向。我需要這樣做,因爲我的佈局包含一些按鈕,它們應該獨立於其佈局進行旋轉,唯一的方法就是通過覆蓋onConfigurationChanged並將相應的動畫添加到每個屏幕方向。我不認爲OrientationEventListener可以工作,因爲設置的方向固定爲縱向。那麼如何從傳感器本身獲取屏幕方向或角度旋轉?如何使用SensorEventListener檢測設備方向?

+0

見我的答案在http://stackoverflow.com/questions/32826227/how-to-determine-device-orientation-from-the-傳感器/ 32837770#32837770。 –

+0

這不是我所需要的。我需要檢測設備動作以根據它旋轉按鈕。佈局保持原樣。 –

+0

你的設備動作是什麼意思?如果設備不平坦,那麼您可以使用上面的鏈接來獲取角度,這將告訴您設備屏幕處於何種方向。您可以通過不將該活動設置爲縱向模式進行測試,然後旋轉屏幕以查看以何種角度它會翻轉到風景。它可能取決於設備。 –

回答

2

即使在固定方向下,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回報什麼,所以如果你有一個自然景觀設備(平板電腦),你必須考慮到這一點,看到How to check device natural (default) orientation on Android (i.e. get landscape for e.g., Motorola Charm or Flipout)

@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); 
     } 
    } 
}