最近再做一個教育類的項目。在做一些學習工具的時候,美工提出了一些要求,大致如下:
其實實現過程也不難,大致就是對一個視圖控件添加一個圓形的背景,然后該視圖進行動畫處理,膨脹的同時,透明度增大,收縮的同時,透明度降低。
我在例子中是使用了TextView,所以首先對TextView添加一個圓形的背景:
android:shape="oval" >
android:height="90dp"
android:width="90dp" />
android:bottom="4dip"
android:left="4dip"
android:right="4dip"
android:top="4dip" />
然后為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);
}
心跳的效果是要不停地膨脹和收縮,所以要開一個線程來處理,每當收縮完畢后重新膨脹。
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();
}
原文:http://blog.csdn.net/u014375869/article/details/46638061