指南针主要是通过方向传感器来获取方位的,使用传感器呢,我们主要用到SensorManager类和Sensor类,通过getSystemService(Context.SENSOR_SERVICE)来初始化SensorManager对象,通过getDefaultSensor(Sensor.TYPE_ORIENTATION)来初始化Sensor对象。在下边我们需要对传感器进行注册,注册方法registerListener(SensorEventListener listener, Sensor sensor,int samplingPeriodUs)的第一个参数我们需要实现这个接口并复写相应的方法,在方法onSensorChanged(SensorEvent event)中我们可以通过event.values[0]来获取方位,这个数值的方位是(正北:0/360 正东:90 正南:180 正西:270)我们获取的是0到360的数值,但是实际上这些数值对应的方位和现实中指南针的方位是对称的,也就是关于Z轴对称。因此我们经常采用-event.values[0]。然后整个轮盘转动我这里采用的是一个自定义的旋转动画来做的,接下来就直接上代码了。
源代码:(码云:https://gitee.com/zhanma/codes/qw28ndj0akcpvf65hl1rg41)
MainActivity:




DefinedRotateAnimation (自定义旋转动画):


MainActivity中44行提到一个bringToFront(),这个方法用来把控件调到前景,因为我在指南针中设置了一个(TextView)指标,方便看出来当前的转到正中央的数值是多少。然后TextView控件和ImageView正好后者把前者覆盖了,因此调用此方法把它调到上一层。自定义动画这块用到initialize方法,用来初始化动画,applyTransformation方法用来实现动画变形(也就是实现动画的效果)
运行截图:


由于模拟器不方便测试这方向传感器,所以我就使用真机调试,上面的运行截图都是从真机上截图下来的。
以上是关于Android指南针的制作。
网友评论