編輯:關於Android編程
6. 為PlayList(播放列表)寫ListView
使用列表視圖(ListView)來顯示播放列表,在drawable文件夾下創建一個xml布局文件並叫做list_selector.xml,這個xml是用於對列表項漸變背景。
list_selector.xml <?xmlversion="1.0"encoding="utf-8"?>
<selectorxmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selector style for listrow -->
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@drawable/gradient_bg"/>
<itemandroid:state_pressed="true"
android:drawable="@drawable/gradient_bg_hover"/>
<itemandroid:state_selected="true"
android:state_pressed="false"
android:drawable="@drawable/gradient_bg_hover"/>
</selector>
在drawable文件夾下創建一個xml布局文件並叫做playlist.xml,這個xml文件是為了顯示列表視圖。
playlist.xml <?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://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>
再在drawable文件夾下創建一個xml布局文件並叫做playlist_item.xml,這個xml文件是為單一列表項顯示歌曲的標題。
playlist_item.xml <?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://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:color="#f3f3f3"/>
</LinearLayout>
通過使用以上布局我們可以實現以下列表視圖通過將數據加載到它。
7. 寫從SDcard讀取mp3文件的類
到目前為止,我們已經完成了player的靜態布局,現在的實際代碼開始。創建一個新的類文件,並將其命名為SongsManager.java。這個類將從設備上的sdcard閱讀所有的文件並且過濾只留帶.mp3後綴的文件。
SongsManager.mp3 packagecom.androidhive.musicplayer;
importjava.io.File;
importjava.io.FilenameFilter;
importjava.util.ArrayList;
importjava.util.HashMap;
publicclassSongsManager {
// SDCard Path
finalString MEDIA_PATH = new String("/sdcard/");
privateArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
publicSongsManager(){
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
publicArrayList<HashMap<String, String>> getPlayList(){
File home = new File(MEDIA_PATH);
if(home.listFiles(newFileExtensionFilter()).length > 0) {
for(File file : home.listFiles(newFileExtensionFilter())) {
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
returnsongsList;
}
/**
* Class to filter files which are having .mp3 extension
* */
classFileExtensionFilterimplements FilenameFilter {
publicbooleanaccept(File dir, String name) {
return(name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
}
8. 為PlayList寫列表視圖
為播放列表的列表視圖創建一個新的活動類,叫做PlayListActivity.java ,PlayListActivity.java 這個類通過使用SongsManager.java類來顯示歌曲列表。
PlayListActivity.java packagecom.androidhive.musicplayer;
importjava.util.ArrayList;
importjava.util.HashMap;
importandroid.app.ListActivity;
importandroid.content.Intent;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.OnItemClickListener;
importandroid.widget.ListAdapter;
importandroid.widget.ListView;
importandroid.widget.SimpleAdapter;
publicclassPlayListActivity extends ListActivity {
// Songs list
publicArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
@Override
publicvoidonCreate(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(inti = 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,newString[] { "songTitle" }, new int[] {
R.id.songTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(newOnItemClickListener() {
@Override
publicvoidonItemClick(AdapterView<?> parent, View view,
intposition,long id) {
// getting listitem index
intsongIndex = 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();
}
});
}
}
9. 輔助類的功能
創建一個新類,叫作Utilities.java,用來處理額外的工作像轉換時間進度百分比,反之亦然。此外,它具有功能將毫秒定時器轉換為時間字符串顯示在播放器的seekbar上。
Utilities.java packagecom.androidhive.musicplayer;
publicclassUtilities {
/**
* Function to convert milliseconds time to
* Timer Format
* Hours:Minutes:Seconds
* */
publicString milliSecondsToTimer(longmilliseconds){
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
inthours = (int)( milliseconds / (1000*60*60));
intminutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
intseconds = (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
returnfinalTimerString;
}
/**
* Function to get Progress percentage
* @param currentDuration
* @param totalDuration
* */
publicintgetProgressPercentage(longcurrentDuration,long totalDuration){
Double percentage = (double)0;
longcurrentSeconds = (int) (currentDuration / 1000);
longtotalSeconds = (int) (totalDuration / 1000);
// calculating percentage
percentage =(((double)currentSeconds)/totalSeconds)*100;
// return percentage
returnpercentage.intValue();
}
/**
* Function to change progress to timer
* @param progress -
* @param totalDuration
* returns current duration in milliseconds
* */
publicintprogressToTimer(intprogress,int totalDuration) {
intcurrentDuration = 0;
totalDuration = (int) (totalDuration / 1000);
currentDuration = (int) ((((double)progress) / 100) * totalDuration);
// return current duration in milliseconds
returncurrentDuration * 1000;
}
}
作者:wangjinyu501
本菜開源的一個自己寫的Demo,希望能給Androider們有所幫助,水平有限,見諒見諒… https://github.com/zhiaixinyang
實現功能:已存在歌曲歌詞下載後續將博文,將實現已下載音樂掃描功能。因為,沒有自己的服務器,所以網絡音樂所有相關功能(包含搜索音樂、下載音樂、下載歌詞)均無法保證時效性,建
1. Fragment概述Fragment從Android v3.0版本開始引入隨著界面布局的復雜化,處理起來也更加的復雜,引入Fragment可以把activity拆分
shape和selector是Android UI設計中經常用到的,比如我們要自定義一個圓角Button,點擊Button有些效果的變化,就要用到shape和select