此例子的指南针在Activity的onResume方法执行时注册传感器的监听器 在onPause方法中执行解除绑定传感器监听器;
目的是为了省电 传感器是很耗电的
布局中就加了一张图片作为指南真的背景 此图片要居中 会转动
1 import android.app.Activity; 2 import android.content.Context; 3 import android.graphics.Matrix; 4 import android.hardware.Sensor; 5 import android.hardware.SensorEvent; 6 import android.hardware.SensorEventListener; 7 import android.hardware.SensorManager; 8 import android.os.Bundle; 9 import android.view.animation.Animation; 10 import android.view.animation.RotateAnimation; 11 import android.widget.ImageView; 12 13 public class MainActivity extends Activity { 14 private ImageView imageView; 15 private SensorManager manager; 16 private SensorListener listener = new SensorListener(); 17 @Override 18 public void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.main); 21 22 imageView = (ImageView) this.findViewById(R.id.imageView); 23 imageView.setKeepScreenOn(true); 24 manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 25 } 26 27 28 @Override 29 protected void onResume() { 30 31 32 Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION); 33 manager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME); 34 super.onResume(); 35 } 36 37 @Override 38 protected void onPause() { 39 manager.unregisterListener(listener); 40 super.onPause(); 41 } 42 43 44 45 private final class SensorListener implements SensorEventListener{ 46 private float predegree = 0; 47 public void onSensorChanged(SensorEvent event) { 48 float degree = event.values[0];//存放了方向值 90 49 RotateAnimation animation = new RotateAnimation(predegree, -degree, 50 Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); 51 52 animation.setDuration(200); 53 imageView.startAnimation(animation); 54 predegree = -degree; 55 } 56 57 public void onAccuracyChanged(Sensor sensor, int accuracy) { 58 } 59 } 60 61 62 }
RotateAnimation (float fromDegrees, float toDegrees, int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)
参数说明
fromDegrees:旋转的开始角度。
toDegrees:旋转的结束角度。
pivotXType:X轴的伸缩模式,可以取值为ABSOLUTE、RELATIVE_TO_SELF、RELATIVE_TO_PARENT。
pivotXValue:X坐标的伸缩值。
pivotYType:Y轴的伸缩模式,可以取值为ABSOLUTE、RELATIVE_TO_SELF、RELATIVE_TO_PARENT。
pivotYValue:Y坐标的伸缩值。
pivotXValue pivotYValue |
为动画相对于物件的X、Y坐标的开始位 | 属性值说明:50%为物件的X或Y方向坐标上的中点位置,相对于自身。”50“代表绝对位置,“50%p”这代表相对于父控件来说。 |
原文:http://www.cnblogs.com/bimingcong/p/4926577.html