最近再做一个教育类的项目,
Android实现心跳的效果
。在做一些学习工具的时候,美工提出了一些要求,大致如下:其实实现过程也不难,大致就是对一个视图控件添加一个圆形的背景,然后该视图进行动画处理,膨胀的同时,透明度增大,收缩的同时,透明度降低。
我在例子中是使用了TextView,所以首先对TextView添加一个圆形的背景:
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android"><size android:height="90dp" android:width="90dp"><solid android:color="@color/color_space_studytools_red"><corners android:radius="180dip"><padding android:bottom="4dip" android:left="4dip" android:right="4dip" android:top="4dip"></padding></corners></solid></size></shape>
然后为TextView添加动画,包括调整大小的ScaleAnimation和调整透明度的AlphaAnimation。调整大小有两个部分,膨胀和收缩。在膨胀完毕后马上收缩,也就是对膨胀的动画进行监听,在onAnimationEnd()方法里面进行收缩,
// 按钮模拟心脏跳动 private void playHeartbeatAnimation(final View heartbeatView) { AnimationSet swellAnimationSet = new AnimationSet(true); swellAnimationSet.addAnimation(new ScaleAnimation(1.0f, 1.8f, 1.0f, 1.8f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)); swellAnimationSet.addAnimation(new AlphaAnimation(1.0f, 0.3f)); swellAnimationSet.setDuration(500); swellAnimationSet.setInterpolator(new AccelerateInterpolator()); swellAnimationSet.setFillAfter(true); swellAnimationSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { AnimationSet shrinkAnimationSet = new AnimationSet(true); shrinkAnimationSet.addAnimation(new ScaleAnimation(1.8f, 1.0f, 1.8f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)); shrinkAnimationSet.addAnimation(new AlphaAnimation(0.3f, 1.0f)); shrinkAnimationSet.setDuration(1000); shrinkAnimationSet.setInterpolator(new DecelerateInterpolator()); shrinkAnimationSet.setFillAfter(false); heartbeatView.startAnimation(shrinkAnimationSet);// 动画结束时重新开始,实现心跳的View } }); heartbeatView.startAnimation(swellAnimationSet); }
心跳的效果是要不停地膨胀和收缩,所以要开一个线程来处理,每当收缩完毕后重新膨胀,
电脑资料
《Android实现心跳的效果》(http://meiwen.anslib.com)。private class HeatbeatThread extends Thread { public void run() { try { sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); } while (true) { runOnUiThread(new Runnable() { public void run() { for (View view : heartbeatViews) { playHeartbeatAnimation(view); } } }); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } } }; }
最后和Activity的生命周期结合,对线程进行开始和结束。
private Thread heartbeatThread; /** * 开始心跳 */ private void startHeartBeat() { if (heartbeatThread == null) { heartbeatThread = new HeatbeatThread(); } if (!heartbeatThread.isAlive()) { heartbeatThread.start(); } } /** * 停止心跳 */ private void stopHeartBeat() { if (heartbeatThread != null && heartbeatThread.isInterrupted()) { heartbeatThread.interrupt(); heartbeatThread = null; System.gc(); } } @Override protected void onResume() { super.onResume(); startHeartBeat(); } @Override protected void onPause() { super.onPause(); stopHeartBeat(); }