Android時時監測手機的旋轉角度 根據旋轉角度確定在什麼角度載入豎屏布局 在什麼時候載入橫屏布局
一、情境描述:
近期開發中遇到個問題,就是我們在做橫豎屏切換的功能時,橫豎屏布局是作業系統去感知的,作為開發員沒法確定Activity在什麼時候載入橫屏布局,在什麼時候載入豎屏布局。因此為了找到載入橫屏布局與豎屏布局的分界點,我特別監控了旋轉螢幕的角度,看在什麼樣的角度會載入橫屏布局,在什麼樣的角度載入豎屏布局。
二、旋轉螢幕度數變化
度數變化,拿著手機順時針旋轉,度數會越變越大。
三、在Activity中監聽手機的旋轉角度,上代碼。
/** * 時時監測螢幕方向是否發生改變 * @author wilson.xiong */class MyOrientationDetector extends OrientationEventListener {public MyOrientationDetector(Context context) {super(context);}@Overridepublic void onOrientationChanged(int orientation) {//如果旋轉螢幕被開啟,則設定螢幕可旋轉//0-57度 125-236度 306-360度 這些區間範圍內為豎屏//58-124度 237-305度 這些區間範圍內為橫屏if ((orientation == -1 || (orientation >= 0) && (orientation <= 57)) || ((orientation >= 125) && (orientation <= 236)) || (orientation >= 306 && orientation <= 360)) {mScreenOrientation = 1;//豎屏} else if ((orientation >= 58 && orientation <= 124) || ((orientation >= 237 && orientation <= 305))) {mScreenOrientation = 0;//橫屏}//mOrientation = orientation;}}
該類的使用方法:
(1)在onResume()中調用enable()方法監聽角度變化
@Overridepublic void onResume() {super.onResume();mDetector.enable();if (!isFirst) {if (GTConfig.instance().hasDickLoaded) {GTSQuote.updateGTSQuoteList();}refreshData();} else {isFirst = false;}}
(2)在onPause()方法中調用disable()方法停止監聽
@Overridepublic void onPause() {super.onPause();mDetector.disable();}