編輯:關於 Android 程式設計
上一篇完成了播放器的靜態版面,本文接著處理「清單」這塊:先做出三個 XML 版面檔,再寫一個掃描 SD 卡的類別,最後用 ListActivity 把資料填進 ListView。
list_selector.xml(放在 drawable 資料夾)——定義列表項的漸變背景:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<!-- Selector style for list row -->
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@drawable/gradient_bg" />
<item android:state_pressed="true"
android:drawable="@drawable/gradient_bg_hover" />
<item android:state_selected="true"
android:state_pressed="false"
android:drawable="@drawable/gradient_bg_hover" />
</selector>
playlist.xml——清單本身的容器:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#242424"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector" />
</LinearLayout>
這裡有個容易忽略的細節:android:id="@android:id/list" 用的是系統內建的 id,因為 ListActivity 會去找這個特定 id 的 ListView。如果改成自訂 id,setListAdapter() 就會出錯。
playlist_item.xml——單一列表項,只顯示歌曲標題:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="@drawable/list_selector"
android:padding="5dp">
<TextView
android:id="@+id/songTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16dp"
android:padding="10dp"
android:textColor="#f3f3f3" />
</LinearLayout>
補充一點:原範例寫的是 android:color="#f3f3f3",但 TextView 沒有這個屬性,字色不會生效。正確的屬性名稱是 android:textColor,上面已經修正。
建立 SongsManager.java,負責掃描 SD 卡並只保留 .mp3 檔。
package com.androidhive.musicplayer;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
public class SongsManager {
// SDCard Path
final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<HashMap<String, String>> songsList =
new ArrayList<HashMap<String, String>>();
// Constructor
public SongsManager() {
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
*/
public ArrayList<HashMap<String, String>> getPlayList() {
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName()
.substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which are having .mp3 extension
*/
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
}
幾個實務上的提醒:MEDIA_PATH 寫死成 /sdcard/ 在現今多儲存分割區與 Android 10 以後的分區儲存模型下常會讀不到,建議改用 Environment.getExternalStorageDirectory() 或 MediaStore 查詢。另外 substring(0, length - 4) 是直接把副檔名砍掉當標題,若檔名不含副檔名會出錯;正式一點的做法是搭配 MediaMetadataRetriever 或 ID3 tag 解析出真正的歌名與歌手。
建立 PlayListActivity.java,用 SongsManager 的結果餵給 ListView。
package com.androidhive.musicplayer;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class PlayListActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> songsList =
new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
ArrayList<HashMap<String, String>> songsListData =
new ArrayList<HashMap<String, String>>();
SongsManager plm = new SongsManager();
// get all songs from sdcard
this.songsList = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, new String[] { "songTitle" },
new int[] { R.id.songTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int songIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
AndroidBuildingMusicPlayerActivity.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
setResult(100, in);
// Closing PlayListView
finish();
}
});
}
}
這裡的資料流是:SongsManager 掃描 → 每首歌包成一個 HashMap(key 為 songTitle / songPath)→ SimpleAdapter 依 playlist_item.xml 把 songTitle 綁到 R.id.songTitle → 點擊時用 putExtra("songIndex", position) 把索引傳給播放 Activity。
順帶一提,中間那個 for 迴圈其實只是把 songsList 逐項複製到 songsListData,沒有加值;直接把 plm.getPlayList() 的結果傳給 SimpleAdapter 即可。保留它是為了示範「可以在這裡插入排序或篩選」的擴充點。
播放器還需要一些時間換算的工具函式:毫秒轉 mm:ss、進度百分比轉時間、時間轉百分比。
package com.androidhive.musicplayer;
public class Utilities {
/**
* Function to convert milliseconds time to
* Timer Format : Hours:Minutes:Seconds
*/
public String milliSecondsToTimer(long milliseconds) {
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours > 0) {
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
/**
* Function to get Progress percentage
*/
public int getProgressPercentage(long currentDuration, long totalDuration) {
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 1000);
long totalSeconds = (int) (totalDuration / 1000);
// calculating percentage
percentage = (((double) currentSeconds) / totalSeconds) * 100;
// return percentage
return percentage.intValue();
}
/**
* Function to change progress to timer
*
* @return current duration in milliseconds
*/
public int progressToTimer(int progress, int totalDuration) {
int currentDuration = 0;
totalDuration = (int) (totalDuration / 1000);
currentDuration = (int) ((((double) progress) / 100) * totalDuration);
// return current duration in milliseconds
return currentDuration * 1000;
}
}
使用時機是這樣的:用 Handler 每 100 毫秒呼叫一次 getProgressPercentage() 更新 SeekBar,同時用 milliSecondsToTimer() 更新時間文字;使用者拖動 SeekBar 時,則用 progressToTimer() 把百分比換回毫秒,丟給 MediaPlayer.seekTo()。
要注意 getProgressPercentage() 在 totalDuration 為 0 時會出現除以零,milliSecondsToTimer() 的分鐘數在超過一小時後不會補零,這兩點在實作時最好補上防呆。
本文原始作者:wangjinyu501
Android 綜合 UI 實作:底部導航、ViewPager、Fragment、Toolbar、DrawerLayout 與 RecyclerView
綜合性 UI 的實作思路 這篇文章整理一個常見的 Android 頁面結構:底部導航、ViewPager、Fragment、Toolbar、DrawerLayout 與
Android 圖片變換入門:用 Matrix 完成旋轉、縮放、平移與傾斜
在 Android 中處理圖片變換時,Matrix 是非常實用的工具。它本質上是一個矩陣,可對圖像進行旋轉、縮放、平移與傾斜等線性變換。 Matrix 的基本操作 Mat
Android 刮刮卡效果實作解析
刮刮卡效果原理 刮刮卡效果的核心是「底圖加上可刮除的遮罩層」。底層顯示獎項或圖片,上層蓋著灰色遮罩。當使用者用手指滑動時,遮罩會沿著手勢路徑被刮開,露出底圖。 Xfer
Android 自訂動態圓環圓形頭像控件
許多 App 都會使用圓形頭像,而搭配動態圓環更能增加視覺層次。本文說明如何以自訂 View 實作一個帶有動態光環的圓形頭像控件。 圓形頭像的基本原理 核心做法是將圖片