欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

轻松实现Android指南针功能

程序员文章站 2024-02-11 21:49:22
本文实例为大家讲解如何轻松实现android指南针功能,分享给大家供大家参考。具体如下: (1)布局文件如下:

本文实例为大家讲解如何轻松实现android指南针功能,分享给大家供大家参考。具体如下:

(1)布局文件如下:

<?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>

所需图片:

轻松实现Android指南针功能

(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];// 存放了方向值 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指南针功能

希望本文所述对大家学习android软件编程有所帮助。