本文实例为大家讲解如何轻松实现android指南针功能,分享给大家供大家参考。具体如下:
(1)布局文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?xml version= "1.0" encoding= "utf-8" ?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:gravity= "center" android:orientation= "vertical" > <imageview android:id= "@+id/imageview" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:src= "@drawable/zn" /> </linearlayout> |
所需图片:
(2)mainactivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
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; import android.view.animation.animation; import android.view.animation.rotateanimation; import android.widget.imageview; public class mainactivity extends activity { private imageview imageview; private sensormanager manager; private sensorlistener listener = new sensorlistener(); @override public void oncreate(bundle savedinstancestate) { super .oncreate(savedinstancestate); setcontentview(r.layout.main); imageview = (imageview) this .findviewbyid(r.id.imageview); imageview.setkeepscreenon( true ); manager = (sensormanager) getsystemservice(context.sensor_service); } @override protected void onresume() { sensor sensor = manager.getdefaultsensor(sensor.type_orientation); manager.registerlistener(listener, sensor, sensormanager.sensor_delay_game); super .onresume(); } @override protected void onpause() { manager.unregisterlistener(listener); super .onpause(); } private final class sensorlistener implements sensoreventlistener { private float predegree = 0 ; public void onsensorchanged(sensorevent event) { float degree = event.values[ 0 ]; // 存放了方向值 90 rotateanimation animation = new rotateanimation(predegree, -degree, animation.relative_to_self, 0 .5f, animation.relative_to_self, 0 .5f); animation.setduration( 200 ); imageview.startanimation(animation); predegree = -degree; } public void onaccuracychanged(sensor sensor, int accuracy) { } } } |
效果如下:
希望本文所述对大家学习android软件编程有所帮助。