今天做了一個橫屏視頻播放,需要實現用戶橫屏的時候,翻轉180度,Activity也跟着翻轉180度,經過查詢資料終於搞定了。把它記下來,免得以后忘記。
step1:
為了防止翻轉的時候重新創建Activity。所以需要在在androidmanifest.xml給Activity配置android:configChanges屬性
代碼如下:
<activity android:name="cc.angis.jy365.activity.VideoPlayerActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />
step2:
最關鍵的就是這里了。因為我們給Activity配置了android:screenOrientation="landscape"屬性,所以當手機翻轉的時候,不會觸發onConfigurationChanged方法了。。。同時也是因為onConfigurationChanged有些問題,所以棄之不用,改用OrientationEventListener來監聽屏幕角度的旋轉這個方法
代碼如下:
class SreenOrientationListener extends OrientationEventListener { public SreenOrientationListener(Context context) { super(context); } @Override public void onOrientationChanged(int orientation) { if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) { return; // 手機平放時,檢測不到有效的角度 } // 只檢測是否有四個角度的改變 if (orientation > 350 || orientation < 10) { // 0度:手機默認豎屏狀態(home鍵在正下方) orientation = 0; } else if (orientation > 80 && orientation < 100) { // 90度:手機順時針旋轉90度橫屏(home建在左側) } else if (orientation > 170 && orientation < 190) { // 手機順時針旋轉180度豎屏(home鍵在上方) orientation = 180; } else if (orientation > 260 && orientation < 280) { // 手機順時針旋轉270度橫屏,(home鍵在右側) } } }
然后分別在Activity的OnPause和OnResume中調用SreenOrientationListener的disable()和enable()方法。
關於onConfigurationChanged方法的問題
@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); }
在該函數中可以通過兩種方法檢測當前的屏幕狀態:
第一種:
判斷newConfig是否等於Configuration.ORIENTATION_LANDSCAPE,Configuration.ORIENTATION_PORTRAIT
當然,這種方法只能判斷屏幕是否為橫屏,或者豎屏,不能獲取具體的旋轉角度。
第二種:
調用this.getWindowManager().getDefaultDisplay().getRotation();該函數的返回值,有如下四種:
Surface.ROTATION_0,
Surface.ROTATION_90,
Surface.ROTATION_180,
Surface.ROTATION_270
其中,Surface.ROTATION_0 表示的是手機豎屏方向向上,后面幾個以此為基准依次以順時針90度遞增。
這種方法有一個Bug,它只能一次旋轉90度,如果你突然一下子旋轉180度,onConfigurationChanged函數不會被調用。
參考資料:http://ticktick.blog.51cto.com/823160/1301209