工具类
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);
点击事件 切换到需要横竖屏切换的fragment处开启其它fragment关闭
Manifest处设置为强制竖屏
theme表示不切换横竖屏不重新创建页面
这是写在碎片中横竖屏的监听
版权声明:本文为weixin_41624865原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。