測試這個功能, 需要啟用自動旋轉屏幕(Auto-rotate screen)功能.
package com.AndroidOrientation;
import android.app.Activity;
import android.content.Context;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.WindowManager;
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();
}
}
@Override
protected 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
String strRotation = "";
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
switch(display.getRotation()){
case(Surface.ROTATION_0):
strRotation = "Surface.ROTATION_0";
break;
case(Surface.ROTATION_90):
strRotation = "Surface.ROTATION_90";
break;
case(Surface.ROTATION_180):
strRotation = "Surface.ROTATION_180";
break;
case(Surface.ROTATION_270):
strRotation = "Surface.ROTATION_270";
break;
}
orientation.setText(String.valueOf(
strRotation + "\n" + arg0));
}
}
}
<?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>
相關文章:
- OrientationEventListener(方向事件監聽器)
沒有留言:
發佈留言