刚刚跟着视频学习了关于Android中传感器的操作示例,利用方向传感器做了一个很简单的指南针应用。。。平时工作项目中很少有用到传感器功能,所以很多都不知道,现在自学些,当作慢慢入门吧。。。
首先贴出软件最终运行效果图
里面用到的这张图片素材,是临时用PPT做的一个,很简陋,能用就行了吧,这不是重点。
下面开始码代码了。。。
布局文件main.xml
<?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:orientation="vertical"
android:background="@android:color/white"
android:gravity="center" >
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img" />
</LinearLayout>
很简单,里面只有一个ImageView控件
MainaActivity类
package com.and.sensor;
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 {
ImageView imgView;
SensorManager manager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgView = (ImageView) findViewById(R.id.img);
imgView.setKeepScreenOn(true);
manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onResume() {
Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
manager.registerListener(sensorListener, sensor,
SensorManager.SENSOR_DELAY_GAME);
super.onResume();
}
SensorEventListener sensorListener = new SensorEventListener() {
private float predegree = 0;
public void onSensorChanged(SensorEvent event) {
float degree = event.values[0];// 数组中的第一个数是方向值
RotateAnimation anim = new RotateAnimation(predegree, -degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(200);
// imgView.setAnimation(anim);//这句错误
imgView.startAnimation(anim);
predegree = -degree;//记录这一次的起始角度作为下次旋转的初始角度
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onPause() {
super.onPause();
manager.unregisterListener(sensorListener);
}
}
注意里面这一句
RotateAnimation anim = new RotateAnimation(predegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
前面两个参数,第一个是旋转的初始角度,第二个要旋转到的角度,因为这里方向传感器判断的是与手机顶部的夹角。试想,如果夹角为90度,起始“北”指向顶部,90度的话,图片需要逆时针旋转90度,所以第二个参数是负的。至于为什么要逆时针转而不是顺时针,这点我也还没有明白。请大神赐教