編輯:關於 Android 開發
用過語音助理類功能的人應該都看過這個效果:按下麥克風後,那個小圖示會像雷達一樣持續明暗閃爍,表示正在聆聽(微軟的 Cortana 是個典型例子)。這種動畫怎麼做的?
實作方法不少,最常見的有兩種:一是準備 n 張圖片輪流切換,二是改變單張圖片的透明度。以下分別說明。
原理很單純——用計時器在背景按固定間隔觸發,透過 Handler 把切換指令送回主執行緒更新畫面。
package com.jereh.musicapplication.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
/**
* Created by zhangdi on 2016/9/1.
* 執行緒池工具類,需要用到執行緒時可直接以類名加方法名呼叫
*/
public class ThreadPoolManager {
/** 執行緒執行器 **/
private static ExecutorService executorService = null;
/** 固定 5 個執行緒 **/
private static int nThreads = 5;
/** 單例 **/
private static ThreadPoolManager taskExecutorPool = null;
/** 初始化執行緒池 **/
static {
taskExecutorPool = new ThreadPoolManager(nThreads * getNumCores());
}
/** 建構子 **/
private ThreadPoolManager(int threads) {
executorService = Executors.newScheduledThreadPool(threads);
}
/** 取得單例 **/
public static ThreadPoolManager getInstance() {
return taskExecutorPool;
}
/** 取得執行緒執行器 **/
public ExecutorService getExecutorService() {
return executorService;
}
/** 取得周期性執行緒執行器 **/
public ScheduledExecutorService getScheduledExcutorService() {
return (ScheduledExecutorService) executorService;
}
/** 取得手機 CPU 核心數 **/
public static int getNumCores() {
return Runtime.getRuntime().availableProcessors();
}
}
用 ScheduledThreadPoolExecutor 而非普通固定池,是因為它原生支援「固定週期重複執行」,正好符合動畫的需求。
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fl"/>
用 FrameLayout 當容器,因為我們是透過 setForeground 來換圖,而非替換子 View。
package com.jereh.musicapplication;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.FrameLayout;
import com.jereh.musicapplication.threadpool.ThreadPoolManager;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class FrameActivity extends AppCompatActivity {
private Timer timer;
FrameLayout frameLayout;
Drawable drawable;
android.os.Handler handler = new android.os.Handler() {
int i = 0;
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
i++;
move(i % 4);
}
super.handleMessage(msg);
}
};
void move(int i) {
drawable = getResources().getDrawable(R.mipmap.ic_launcher, null);
Drawable drawable1 = getResources().getDrawable(R.mipmap.dd1, null);
Drawable drawable2 = getResources().getDrawable(R.mipmap.dd2, null);
Drawable drawable3 = getResources().getDrawable(R.mipmap.dd3, null);
switch (i) {
case 0:
frameLayout.setForeground(drawable);
break;
case 1:
frameLayout.setForeground(drawable1);
break;
case 2:
frameLayout.setForeground(drawable2);
break;
case 3:
frameLayout.setForeground(drawable3);
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame);
frameLayout = (FrameLayout) findViewById(R.id.fl);
timer = new Timer();
// 寫法一:使用 Timer
// timer.schedule(new TimerTask() {
// @Override
// public void run() {
// handler.sendEmptyMessage(1);
// }
// }, 0, 500);
// 寫法二:使用自訂執行緒池(較推薦)
ThreadPoolManager
.getInstance()
.getScheduledExcutorService()
.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
}, 0, 500, TimeUnit.MILLISECONDS);
// 第二個參數是延遲多久開始,第三個是每隔多久顯示下一張
}
@Override
protected void onDestroy() {
if (timer != null) {
timer.cancel();
}
super.onDestroy();
}
}
這裡示範了兩種排程方式。Timer 簡單直觀,但有一個眾所皆知的缺點:它只有單一執行緒,任一任務拋出未捕捉的例外就會導致整個 Timer 死亡。自訂執行緒池在這方面更穩健,也更容易擴充。
這種做法的明顯缺點是必須準備 n 張圖。若只有單張素材,就得走第二條路。
/**
* 從不透明漸變到全透明
* @return
*/
public Animation getAlphaAnimationIn() {
// AlphaAnimation 主要用來改變透明度
// 透明度:1.0 為不透明,0 為完全透明
Animation animation = new AlphaAnimation(1.0f, 0);
// 設定插值器,用來修飾動畫的變化率
animation.setInterpolator(new DecelerateInterpolator());
// 設定動畫執行時間
animation.setDuration(2000);
return animation;
}
/**
* 從全透明漸變到不透明
* @return
*/
public Animation getAlphaAnimationOut() {
Animation animation = new AlphaAnimation(0, 1.0f);
animation.setInterpolator(new DecelerateInterpolator());
animation.setDuration(2000);
return animation;
}
關鍵在於「A 結束時啟動 B,B 結束時啟動 A」,如此一來就能形成無限循環。
voiceState1.setAnimation(animationIn);
voiceState1.setAnimation(animationOut);
/**
* 監聽動畫,實現動畫之間的切換
*/
animationOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
voiceState1.startAnimation(animationIn);
}
@Override
public void onAnimationRepeat(Animation animation) { }
});
animationIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
voiceState1.startAnimation(animationOut);
}
@Override
public void onAnimationRepeat(Animation animation) { }
});
如此一來,單張圖片也能做出持續閃爍的效果。
多幀切換適合真正有「動作變化」的動畫,例如角色走路、載入轉圈;缺點是要準備多張素材,APK 體積會增加。
Alpha 動畫只需一張圖,程式碼也短,適合單純的呼吸燈、閃爍提示。
不過要說的是,這兩種做法在當今都有更簡潔的替代方案:
寫法一:AnimationDrawable(多幀)
把 n 張圖寫成一個 XML,完全不用寫 Java:
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@mipmap/dd1" android:duration="500" />
<item android:drawable="@mipmap/dd2" android:duration="500" />
<item android:drawable="@mipmap/dd3" android:duration="500" />
<item android:drawable="@mipmap/dd4" android:duration="500" />
</animation-list>
Java 端只需 ((AnimationDrawable) iv.getBackground()).start()。
寫法二:属性動畫(透明度)
// 單行完成無限來回閃爍 ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "alpha", 1.0f, 0.3f); animator.setDuration(800); animator.setRepeatCount(ValueAnimator.INFINITE); animator.setRepeatMode(ValueAnimator.REVERSE); animator.start();
用 REVERSE 模式,系統會自動「到頭後反向往回播」,根本不需要自己寫兩個動畫互相接力。這比監聽互喚的寫法簡潔太多,也更不容易出 bug(例如忘記在 onPause 停止動畫導致背景持續耗電)。
最後提醒:動畫一律要在 onPause 或 onStop 中停止,否則 App 退到背景後仍在跑動畫,白白消耗電量。
安卓六大基礎佈局詳解:從線性到幀佈局
安卓六大基礎佈局詳解:從線性到幀佈局 今天我們來系統梳理安卓最基礎的幾種佈局方式,它們是搭建每一個界面的基石: 1. 線性佈局(LinearLayout)2. 相對佈局(
Android 簽名機制解析:APK 簽名驗證流程詳解
一、前言在 Android 中,APK 的簽名機制不只是打包時的產物,更是安裝階段安全校驗的基礎。本文將以安裝流程為切入點,說明系統如何逐步驗證 APK 內的檔案、摘要資
Android 仿即刻首頁垂直滾動圖:自訂 ViewGroup 動畫
Android 仿即刻首頁垂直滾動圖:自訂 ViewGroup 動畫 首頁頂部垂直輪播圖片是常見的視覺效果。本文以仿即刻 App 的垂直滾動圖為例,說明如何透過自訂 Vi
Android NDK 目錄結構詳解與環境變數設定
Android NDK 目錄結構詳解與環境變數設定 交叉編譯:指在一個平台上編譯出另一個平台上可執行的本地程式碼。 CPU 平台:arm、x86、mips;作業系統平台: