為了讓App有趣一點,所以這次要加上音效(SoundPool)。

但又不想讓使用者覺得動畫太冗長,故在設定的地方做旋轉動畫與音效控制的開關(Switch)。

首先,先在res資料夾下建立raw資料夾,並把要使用的音效檔放進去。

但要注意,檔案大小不可超過1MB,以及檔案格式最好為OGG,以避免某些型號的手機會有雜音,但此次是採用WAV檔。

bmi_calculator_0005.png  

MainActivity宣告SoundPool,以及欲撥放的檔案名稱soundLoop、soundDecide與soundVolume。

private SoundPool sound;
private soundLoop loop, soundDecide, soundVolume;

onCreate()時要記得把音效檔載入,loop為圖片旋轉時的音效,decide為圖片停止時的音效。

soundLoop = sound.load(this, R.raw.loop, 1);
soundDecide = sound.load(this, R.raw.decide, 1);

既然圖片是要旋轉時才撥放音效,故在calculateBmi()中加上音效撥放,第一參數為要撥放的變數,第二參數為左聲道音量控制,第三參數為右聲道音量控制,第四參數為優先權,第五參數為是否要循環播放,第六參數為播放速率。

sound.play(this.soundLoop, soundVolume, soundVolume, 0, 0, 1);

如果音效太長,想要停止時可以使用:

sound.pause(this.soundLoop);

至此,音效的播放告一段落,等會兒回來處理音量控制。

新增SettingActivity,其Layout如下。

bmi_calculator_0006.png

 

很簡單的兩個Switch與其圖片,此處的設計是當關閉動畫時,音效也隨之關閉。

但若要使用Switch,則在AndroidManifest中最小版本的宣告不可小於14。

bmi_calculator_0007.png

 

但當動畫開啟時,音效可獨立關閉。

bmi_calculator_0008.png  

對Switch而言,因為有按下與滑動兩種操作方式,若跟Button一樣在XML中採用onClick的方式,就只能判斷到按下,而無法判斷到滑動。

因此這裡採用OnCheckedChangeListener,以改變動畫Switch為例:

OnCheckedChangeListener switchAnima_listener = new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked) {
profile.edit().putBoolean(animaField, true).commit();
profile.edit().putBoolean(soundField, true).commit();
} else {
profile.edit().putBoolean(animaField, false).commit();
profile.edit().putBoolean(soundField, false).commit();
}
readData();
}
};

別忘了要設定listener,switchAnima.setOnCheckedChangeListener(switchAnima_listener);

SettingActivity到此告一段落,回到MainActivity處理音效控制。

在readData()中,判斷音效控制是否為true,若是true的話,音量為5;若是false,則音量為0。

if (profile.getBoolean(soundField, true)) soundVolume = 5;
else soundVolume = 0;

如此一來音量控制完成了,動畫播放也一樣,當動畫開關為false時,跳過動畫旋轉的部分,直接給予正確的值即可。

if (profile.getBoolean(animaField, true)) {
rotate(0, 360, 100, -1); //假旋轉
sound.play(this.soundLoop, soundVolume, soundVolume, 0, 0, 1);
new CountDownTimer(2200, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
rotatePrepare(results);
}
}.start();
} else {
rotatePrepare(results);
}

關於此次的code可以到這裡進行下載。

講著講著就完成2/3了,下篇將提到如何把資料存到database。

arrow
arrow
    文章標籤
    android BMI計算機
    全站熱搜

    scarletdream 發表在 痞客邦 留言(0) 人氣()