在調用了setRequestedOrientation之後,手機螢幕的旋轉不觸發onConfigurationChanged方法,這個時候需要再調用一次
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);方法,讓他開啟自動旋轉事件
如代碼:
- /**
- * 開啟監聽器
- */
- private final void startListener() {
- mOrientationListener = new OrientationEventListener(this) {
- @Override
- public void onOrientationChanged(int rotation) {
-
- if (startRotation == -2) {//初始化角度
- startRotation = rotation;
- }
- //變化角度大於30時,開啟自動旋轉,並關閉監聽
- int r = Math.abs(startRotation - rotation);
- r = r > 180 ? 360 - r : r;
- if (r > 30) {
- //開啟自動旋轉,回應螢幕旋轉事件
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
- this.disable();
- }
- }
- };
- }
/**
* 開啟監聽器
*/
private final void startListener() {
mOrientationListener = new OrientationEventListener(this) {
@Override
public void onOrientationChanged(int rotation) {
if (startRotation == -2) {//初始化角度
startRotation = rotation;
}
//變化角度大於30時,開啟自動旋轉,並關閉監聽
int r = Math.abs(startRotation - rotation);
r = r > 180 ? 360 - r : r;
if (r > 30) {
//開啟自動旋轉,回應螢幕旋轉事件
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
this.disable();
}
}
};
}
在手動旋轉按鈕監聽事件中寫下
- //設置完之後變成強制設定為橫屏或縱屏,如同AndroidManifest.xml中設置了android:screenOrientation
- if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- }else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
- }
- //2秒後開啟螢幕旋轉監聽,用來開啟自動旋轉,回應螢幕旋轉事件
- orientationHandler.sendEmptyMessageDelayed(0, 2000);
//設置完之後變成強制設定為橫屏或縱屏,如同AndroidManifest.xml中設置了android:screenOrientation
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
//2秒後開啟螢幕旋轉監聽,用來開啟自動旋轉,回應螢幕旋轉事件
orientationHandler.sendEmptyMessageDelayed(0, 2000);
最後設置handler
- private OrientationEventListener mOrientationListener; // 螢幕方向改變監聽器
- private int startRotation;
- Handler orientationHandler = new Handler(){
- public void handleMessage(Message msg) {
- startRotation = -2;
- mOrientationListener.enable();
- };
- };
private OrientationEventListener mOrientationListener; // 螢幕方向改變監聽器
private int startRotation;
Handler orientationHandler = new Handler(){
public void handleMessage(Message msg) {
startRotation = -2;
mOrientationListener.enable();
};
};