首先在AndroidManifest.xml中,对需要设置的Activity加上如下两条属性:
android:configChanges="orientation|keyboard" (转屏时不重置Activity,
若设置了此项,则无法为横向和纵向分别设置不同的布局。因为转屏时不会删除并重新加载)
android:screenOrientation="sensor" (开启重力传感器)
转屏函数:
import android.content.pm.ActivityInfo;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
//强制指定纵向 value为5
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
//强制指定反方向纵向 value为9
重力传感器监测:
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
public class asd extends Activity{
SensorManager mManager;
Sensor mSensor;
SensorEventListener mListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(5);//初始化屏幕方向
mManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
};
public void onSensorChanged(SensorEvent event) {
float x = event.values[SensorManager.DATA_X];
float y = event.values[SensorManager.DATA_Y];
float z = event.values[SensorManager.DATA_Z];
setCustomOrientation(x, y, z);
};
};
mManager.registerListener(mListener, mSensor, SensorManager.SENSOR_DELAY_GAME);
}
public void setCustomOrientation(float x, float y, float z) {
if(y > 1.5)
{
//setRequestedOrientation(
// ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setRequestedOrientation(5);
}
else if(y < -1.5)
{
setRequestedOrientation(9);
}
};
@Override
protected void onResume() {
super.onResume();
mManager.registerListener(mListener, mSensor,
SensorManager.SENSOR_DELAY_GAME);
};
@Override
protected void onPause() {
super.onPause();
mManager.unregisterListener(mListener);
};
}