剛剛跟著視頻學習了關於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;@Overridepublic 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);}@Overrideprotected 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) {}};@Overrideprotected 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度,所以第二個參數是負的。至於為什麼要逆時針轉而不是順時針,這點我也還沒有明白。請大神賜教