这是一个多用途类,用于轻松管理屏幕方向更改:
public class OrientationManager extends OrientationEventListener {
public enum ScreenOrientation {
REVERSED_LANDSCAPE, LANDSCAPE, PORTRAIT, REVERSED_PORTRAIT
}
public ScreenOrientation screenOrientation;
private OrientationListener listener;
public OrientationManager(Context context, int rate, OrientationListener listener) {
super(context, rate);
setListener(listener);
}
public OrientationManager(Context context, int rate) {
super(context, rate);
}
public OrientationManager(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
if (orientation == -1){
return;
}
ScreenOrientation newOrientation;
if (orientation >= 60 && orientation <= 140){
newOrientation = ScreenOrientation.REVERSED_LANDSCAPE;
} else if (orientation >= 140 && orientation <= 220) {
newOrientation = ScreenOrientation.REVERSED_PORTRAIT;
} else if (orientation >= 220 && orientation <= 300) {
newOrientation = ScreenOrientation.LANDSCAPE;
} else {
newOrientation = ScreenOrientation.PORTRAIT;
}
if(newOrientation != screenOrientation){
screenOrientation = newOrientation;
if(listener != null){
listener.onOrientationChange(screenOrientation);
}
}
}
public void setListener(OrientationListener listener){
this.listener = listener;
}
public ScreenOrientation getScreenOrientation(){
return screenOrientation;
}
public interface OrientationListener {
public void onOrientationChange(ScreenOrientation screenOrientation);
}
}
这是更简单、可重用的方式,并且您还可以获得 REVERSE_LANDSCAPE 和 REVERSE_PORTRAIT 方向。
您必须实现 OrientationListener,以便仅在发生方向更改时收到通知。
不要忘记调用orientationManager.enable()来开始方向跟踪,然后调用orientationManager.disable()(这两个方法继承自OrientationEventListener类)
更新:用例示例
MyFragment extends Fragment implements OrientationListener {
...
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
orientationManager = new OrientationManager(getActivity(), SensorManager.SENSOR_DELAY_NORMAL, this);
orientationManager.enable();
}
@Override
public void onOrientationChange(ScreenOrientation screenOrientation) {
switch(screenOrientation){
case PORTRAIT:
case REVERSED_PORTRAIT:
MainActivityBase.getInstance().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case REVERSED_LANDSCAPE:
MainActivityBase.getInstance().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
case LANDSCAPE:
MainActivityBase.getInstance().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
}
}