This article examples for you to explain how to easily achieve the Android Compass function, share for everyone to reference. Specifically as follows:
(1) The layout file is as follows:
<?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>
Picture required:
(2) Mainactivity.java
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];//Store directional value rotateanimation a Nimation = new Rotateanimation (Predegree,-degree, Animation.relative_to_self, 0.5f, Animation.relativ
E_to_self, 0.5f);
Animation.setduration (200);
Imageview.startanimation (animation);
Predegree =-degree;
public void onaccuracychanged (Sensor Sensor, int accuracy) {}}}
The effect is as follows:
I hope this article will help you learn about Android software programming.