點選按鈕切換橫豎屏
阿新 • • 發佈:2019-02-18
1.定義如下變數
private OrientationEventListener mOrientationListener; // 螢幕方向改變監聽器
private boolean mIsLand = false; // 是否是橫屏
private boolean mClick = false; // 是否點選
private boolean mClickLand = true; // 點選進入橫屏
private boolean mClickPort = true; // 點選進入豎屏
2.初始化時呼叫如下程式碼:
3.ondestory方法中,關閉監聽/** * 開啟監聽器 */ private final void startListener() { mOrientationListener = new OrientationEventListener(this) { @Override public void onOrientationChanged(int rotation) { // 設定豎屏 if (((rotation >= 0) && (rotation <= 45)) || (rotation >= 315)||((rotation>=135)&&(rotation<=225))) {//portrait if (mClick) { if (mIsLand && !mClickLand) { return; } else { mClickPort = true; mClick = false; mIsLand = false; } } else { if (mIsLand) { setPortait(); mIsLand = false; mClick = false; } } } // 設定橫屏 else if (((rotation > 45) && (rotation < 135))||((rotation>225)&&(rotation<315))) {//landscape if (mClick) { if (!mIsLand && !mClickPort) { return; } else { mClickLand = true; mClick = false; mIsLand = true; } } else { if (!mIsLand) { setLanscape(); mIsLand = true; mClick = false; } } } } }; mOrientationListener.enable(); }
mOrientationListener.disable();
4.點選切換按鈕執行如下方法:
public void changeScreen() { mClick = true; if (!mIsLand) { setLanscape(); mIsLand = true; mClickLand = false; } else { setPortait(); mIsLand = false; mClickPort = false; } }
5.返回鍵監聽:
//點選返回按鈕及系統返回
private void onActivityBack() {
if (isLandscape()) {//水平
if (isLandscape()) {
setPortait();
}else{
setLanscape();
}
} else {//豎直方向
finish();
}
}
6.oncfigurationChanged方法修改
@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Utils.printLog("lb","onConfigurationChanged====="); if (isLandscape()) {//水平 Utils.printLog("lb","onConfigurationChanged===水平=="); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); }else if (isPortrait()) {//豎直方向 Utils.printLog("lb","onConfigurationChanged===豎直=="); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } //此處可以隱藏顯示你的佈局 setLandscapeOrPortraitLayout(); }