在程式onCreate()方法中建構MyOrientationEventListener實體,並啟用OrientationEvent監聽作業。
MyOrientationEventListener myOrientationEventListener;
Display display;
TextView txtmsg;
@Override
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtmsg = (TextView) findViewById(R.id.textView1);
display = getWindowManager().getDefaultDisplay();
myOrientationEventListener = new
MyOrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL);
if (myOrientationEventListener.canDetectOrientation())
myOrientationEventListener.enable();
else
Toast.makeText(MainActivity.this, "Can't Detect Orientation!", Toast.LENGTH_LONG).show();
}
實作MyOrientationEventListener.onOrientationChanged()方法,透過Display. getOrientation()方法取得螢幕方位代碼,並將螢幕方位訊息顯示在textView1元件。
@Override
public void
onOrientationChanged(int orientation) {
switch (display.getOrientation()){
case 0:
txtmsg.setText("Portrait");
break;
case 1:
txtmsg.setText("Landscape - Counterclockwise");
break;
case 3:
txtmsg.setText("Landscape - Clockwise");
break;
}
}
程式結束前關閉OrientationEventListener()監聽作業。由Source子功能表點選「Override/Implement Methods...」命令建立onDestroy()程式框架,並調用OrientationEventListener.disable()方法。
@Override
protected void
onDestroy() {
super.onDestroy();
myOrientationEventListener.disable();
}