码迷,mamicode.com
首页 > 其他好文 > 详细

感重力旋转屏幕

时间:2014-09-12 17:21:03      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:感重力旋转屏幕   感重力   屏幕旋转   

bubuko.com,布布扣bubuko.com,布布扣





















这个是效果图,点击这里下载源码;

实现该功能只需要实现三部曲:第一步重写Handler:

public class ChangeOrientationHandler extends Handler {

	private Activity activity;

	public ChangeOrientationHandler(Activity ac) {
		super();
		activity = ac;
	}
	
	@Override
	public void handleMessage(Message msg) {  
		if (msg.what==888) {
			int orientation = msg.arg1;
			if (orientation>45&&orientation<135) {
				activity.setRequestedOrientation(8);
			}else if (orientation>135&&orientation<225){
				activity.setRequestedOrientation(9);
			}else if (orientation>225&&orientation<315){
				activity.setRequestedOrientation(0);
			}else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){
				activity.setRequestedOrientation(1);
			}
		}
		
		super.handleMessage(msg);        		
	}
	
}
第二步重写SensorEventListener:
public class OrientationSensorListener implements SensorEventListener {
	 private static final int _DATA_X = 0;
     private static final int _DATA_Y = 1;
     private static final int _DATA_Z = 2;
     
     public static final int ORIENTATION_UNKNOWN = -1;
     
     private Handler rotateHandler;
     
     
     
	public OrientationSensorListener(Handler handler) {
		rotateHandler = handler;
	}

	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	public void onSensorChanged(SensorEvent event) {
		float[] values = event.values;
        int orientation = ORIENTATION_UNKNOWN;
        float X = -values[_DATA_X];
        float Y = -values[_DATA_Y];
        float Z = -values[_DATA_Z];        
        float magnitude = X*X + Y*Y;
        // Don't trust the angle if the magnitude is small compared to the y value
        if (magnitude * 4 >= Z*Z) {
            float OneEightyOverPi = 57.29577957855f;
            float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
            orientation = 90 - (int)Math.round(angle);
            // normalize to 0 - 359 range
            while (orientation >= 360) {
                orientation -= 360;
            } 
            while (orientation < 0) {
                orientation += 360;
            }
        }
        
        if (rotateHandler!=null) {
			rotateHandler.obtainMessage(888, orientation, 0).sendToTarget();
		}

	}

}

第三步到MainActivity.java中配置:XXXXXX     ~~~~搞定!

感重力旋转屏幕

标签:感重力旋转屏幕   感重力   屏幕旋转   

原文地址:http://blog.csdn.net/junhuahouse/article/details/39230277

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!