传感器(抖一抖)

2018-07-02  本文已影响0人  Summer_27d1

xml
···
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="{relativePackage}.{activityClass}" >

<ImageView
    android:id="@+id/img"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:src="@drawable/ic_launcher"
    android:visibility="invisible"
     />

</RelativeLayout>

···
MainActivity
···
package com.example.ytest10_sensor;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener {

private SensorManager sensorManager;
private Sensor defaultSensor;
private ImageView img;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);

    //1.获取传感器
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
   //2.获取指定传感器
    defaultSensor = sensorManager.getDefaultSensor(1);

}
  //3.注册sensorManager监听
@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    sensorManager.registerListener(this,defaultSensor, SensorManager.SENSOR_DELAY_NORMAL);
    
}

// 当传感器发生改变时走该监听
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
Toast.makeText(getApplicationContext(), "x:"+x+"y: "+y+"z: "+z, 1).show();
if (Math.abs(x)>14|| Math.abs(y)>14||Math.abs(z)>14) {

        ObjectAnimator rotation = ObjectAnimator.ofFloat(img, "rotation", 0,365*5);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(img, "alpha", 0,1);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(img, "scaleX", 0,0.8f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(img, "scaleY", 0,0.8f);
      AnimatorSet animatorSet = new AnimatorSet();
      img.setVisibility(View.VISIBLE);
      animatorSet.playTogether(rotation,alpha,scaleX,scaleY);
      animatorSet.setDuration(2000);
      animatorSet.start();
      
    }
    
    
    
}

// 当传感器速率发生改变时走这个监听
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub

}

}

···

上一篇 下一篇

猜你喜欢

热点阅读