这个demo模仿的是微信的摇一摇,是一个完整的demo,下载地址在最下面.下面是demo截图:
步驟:
1.手机摇动监听,首先要实现传感器接口SensorEventListener.
/**开始重力传感器的检测*/ public void start() { // 获得传感器管理器 SensorManager sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); if (sensorManager != null) { // 获得重力传感器 sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); } // 注册 if (sensor != null) { sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME); } }
2.启动手掌开合动画,这个手掌其实是上下两部分组成的,分别开启一个上下垂直动画.
/** 摇一摇手掌上部分动画 */ public AnimationSet getUpAnim(Handler handler) { AnimationSet animup = new AnimationSet(true); TranslateAnimation mytranslateanimup0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -0.8f); mytranslateanimup0.setDuration(OPEN_TIME); mytranslateanimup0.setAnimationListener(getLineVisibleListener(handler)); TranslateAnimation mytranslateanimup1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, +0.8f); mytranslateanimup1.setDuration(CLOSE_TIME); mytranslateanimup1.setStartOffset(OFFSET_TIME); mytranslateanimup1.setInterpolator(new AccelerateInterpolator(1)); mytranslateanimup1.setAnimationListener(getLineGoneListener(handler)); animup.addAnimation(mytranslateanimup0); animup.addAnimation(mytranslateanimup1); return animup; } /** 摇一摇手掌下部分动画 */ public AnimationSet getDownAnim() { AnimationSet animdn = new AnimationSet(true); TranslateAnimation mytranslateanimdn0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, +0.8f); mytranslateanimdn0.setDuration(OPEN_TIME); TranslateAnimation mytranslateanimdn1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -0.8f); mytranslateanimdn1.setDuration(CLOSE_TIME); mytranslateanimdn1.setStartOffset(OFFSET_TIME); mytranslateanimdn1.setInterpolator(new AccelerateInterpolator(1)); animdn.addAnimation(mytranslateanimdn0); animdn.addAnimation(mytranslateanimdn1); return animdn; }
3.结果页动画,重新摇一摇时,也会启动一个动画将结果页移动到最下方然后消失.就跟微信摇到了人以后,弹出的个人信息卡一样.
demo下载地址:http://files.cnblogs.com/files/wangyuehome/Shake.zip