手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >轻松实现Android指南针功能
轻松实现Android指南针功能
摘要:本文实例为大家讲解如何轻松实现Android指南针功能,分享给大家供大家参考。具体如下:(1)布局文件如下:所需图片:(2)MainActi...

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

(1)布局文件如下:

<"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指南针功能1

(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指南针功能2

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

【轻松实现Android指南针功能】相关文章:

Android应用中的组件功能

基于Android中实现定时器的3种解决方法

Android 异步加载图片的实例代码

Android内存调试命令

Android 情景模式的设置代码

android自动化测试中实现长按并拖动

android WebView加载html5介绍

Android设置桌面背景图片的实现方法

Android 路径查询

Android按返回键退出程序但不销毁代码

精品推荐
分类导航