Android手機旋轉的時候(系統的旋轉選項打開的情況下),Activity會進行重構(調用onDestory和onCreate),接着進行屏幕的切換(從橫屏切換到豎屏或者相反)。
如果要做一個在屏幕旋轉時屏幕上的View跟隨其屏幕旋轉,提供兩種思路
思路1
強制屏幕旋轉的時候,讓Activity不調用其onDestory和onCreate方法,而調用其onConfigurationChanged方法,根據屏幕方向進行不同的處理
步驟一
在AndroidManifest.xml的<application>標籤中配置
android:configChanges="orientation|keyboardHidden"
在Android 3.2(API 13)上添加screenSize。
步驟二
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
// do something when portrait
} else {
// do something when landscape
}
}
在<activity>中不能聲明screenOrientation,否則屏幕不會進行橫豎屏且切換。
缺點:橫屏和豎屏必須有不同的佈局,否則會佈局錯亂。
思路2
註冊Sensor監聽器,這樣手機旋轉的時候會回調其旋轉的角度,再對角度進行處理
步驟1
爲Activity註冊方向監聽器
<pre name="code" class="java">OrientationEventListener <span style="font-family: Arial, Helvetica, sans-serif;">mOrientationListener = new OrientationEventListener(Context,SensorManager.SENSOR_DELAY_UI)</span>
第一個參數是上下文Context對象,第二個參數是回調頻率的快慢,此處選擇頻率最低的SENSOR_DELAY_UI
步驟2
啓動監聽器
一般會選擇在Activity生命週期開始onStart方法內調用啓動監聽器,
<span style="white-space:pre"> </span>@Override
protected void onStart() {
super.onStart();
if (mOrientationListener != null) {
mOrientationListener.enable();
}
}
結束onStop方法內註銷監聽器
@Override
protected void onStop() {
if (mOrientationListener != null) {
mOrientationListener.disable();
}
super.onStop();
}
步驟3
覆蓋監聽方法
@Override
public void onOrientationChanged(int orientation) {
// 接口回調參數下方是0度,左邊是270度
// 動畫接口下方是0度,左邊是90度,而且360在0偏 右邊
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
return; // 手機平放時,檢測不到有效的角度
}
// 只檢測是否有四個角度的改變
if (orientation < 60 && orientation > 30) { // 動畫0度與接口360度相反,增加下限抵消0度影響
orientation = 360;
} else if (orientation > 70 && orientation < 110) { // 動畫90度與接口270度相反
orientation = 270;
} else if (orientation > 160 && orientation < 200) { // 180度
orientation = 180;
} else if (orientation > 240 && orientation < 300) {
orientation = 90;
} else if (orientation > 320 && orientation < 340) {// 減少上限減少360度的影響
orientation = 0;
} else {
return;
}
if (mOldOriental != orientation) {
ObjectAnimator
.ofFloat(mTest, "Rotation", mOldOriental,
orientation).setDuration(700).start();
mOldOriental = orientation;
}
}
接口回調的參數圖解
逆時針旋轉到90°
繼續逆時針旋轉到180°
繼續逆時針旋轉到270度
注意:從270到359度是需要小心的地方,因爲處於0度的位置會經常在[350,10]之間搖晃。