OrientationEventListener(方向事件監聽器)

时间:2021-12-27 00:07:36

                                                                       
  
 
OrientationEventListener(方向事件監聽器)是一個當方向發生變化時, 從 SensorManager(傳感器管理程序)接收通知的輔助類.



?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 package
com.AndroidOrientation;
 import
android.app.Activity;
import
android.content.Context;
import
android.hardware.SensorManager;
import
android.os.Bundle;
import
android.view.OrientationEventListener;
import
android.widget.TextView;
import
android.widget.Toast;
 public
class
AndroidOrientation extends
Activity{
 TextView
orientation;
MyOrientationEventListener
myOrientationEventListener;
    /** Called when the activity is first created. */   @Override   public
void
onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);       setContentView(R.layout.main);       orientation = (TextView)findViewById(R.id.orientation);              myOrientationEventListener =        new
MyOrientationEventListener(
this, SensorManager.SENSOR_DELAY_NORMAL);
              if
(myOrientationEventListener.canDetectOrientation()){
        myOrientationEventListener.enable();       }else{        Toast.makeText(AndroidOrientation.this,          "Can't Detect Orientation!",          Toast.LENGTH_LONG).show();       }   }      @Overrideprotected
void
onDestroy() {
 // TODO Auto-generated method stub super.onDestroy(); myOrientationEventListener.disable();} class
MyOrientationEventListener
extends
OrientationEventListener{
  public
MyOrientationEventListener(Context context,
int
rate) {
  super(context, rate);  // TODO Auto-generated constructor stub }  @Override public
void
onOrientationChanged(int
arg0) {
  // TODO Auto-generated method stub  orientation.setText(String.valueOf(arg0)); }       }}


?
123456789101112131415161718 <?xml
version
="1.0"
encoding
="utf-8"?>
<LinearLayout
xmlns:android
="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"   android:layout_width="fill_parent"   android:layout_height="fill_parent"   ><TextView   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:text="@string/hello"   /><TextView   android:id="@+id/orientation"   android:layout_width="fill_parent"   android:layout_height="wrap_content"   /></LinearLayout>