工具類
import android.app.Activity;
import android.app.Fragment;
import android.content.pm.ActivityInfo;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.OrientationEventListener;
import java.lang.ref.WeakReference;
/**
* Created by Administrator on 2021/4/21 0021.
*/
public class SwitchDoIt{
private OrientationEventListener landOrientationListener
private OrientationEventListener portOrientationListener
private WeakReference<Activity> weakReference
private boolean portLock = false;
private boolean landLock=false;
public SwitchDoIt(final Activity activity) {
this.weakReference = new WeakReference(activity);
//橫屏
this.landOrientationListener = new OrientationEventListener(activity, 3) {
public void onOrientationChanged(int orientation) {
Log.d(MySensorHelper.TAG, "mLandOrientationListener");
if(orientation < 100 && orientation > 80 || orientation < 280 && orientation > 260) {
if(!MySensorHelper.this.isLandLock) {
Activity mActivity = MySensorHelper.this.weakReference.get();
if(mActivity != null) {
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
landLock=true;
portLock=false;
}
}
}
}
};
//豎屏
this.portOrientationListener = new OrientationEventListener(activity, 3) {
public void onOrientationChanged(int orientation) {
Log.w(MySensorHelper.TAG, "mPortOrientationListener");
if(orientation < 10 || orientation > 350 || orientation < 190 && orientation > 170) {
if(!MySensorHelper.this.isPortLock) {
Activity mActivity = MySensorHelper.this.weakReference.get();
if(mActivity != null) {
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
portLock=true;
landLock=false;
}
}
}
}
};
}
//關閉橫豎屏切換
public void disable(Activity activity) {
Log.e(TAG, "disable");
this.portOrientationListener.disable();
this.landOrientationListener.disable();
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
//打開橫豎屏切換
public void enable(){
this.portOrientationListener.enable();
this.landOrientationListener.enable();
}
}
使用方法:
在Activity開啟
MySensorHelper mySensorHelper=new MySensorHelper(this);
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TPR5kMnRkT5lFVNBDOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLwMTM4QDMzgTMxIDNwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
點選事件 切換到需要橫豎屏切換的fragment處開啟其它fragment關閉
Manifest處設定為強制豎屏
theme表示不切換橫豎屏不重新建立頁面
這是寫在碎片中橫豎屏的監聽