6. 为PlayList(播放列表)写ListView
使用列表视图(ListView)来显示播放列表,在drawable文件夹下创建一个xml布局文件并叫做list_selector.xml,这个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> |
<?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> |
<?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后缀的文件。
packagecom.androidhive.musicplayer; importjava.io.File; importjava.io.FilenameFilter; importjava.util.ArrayList; importjava.util.HashMap; publicclassSongsManager { // SDCard Path finalString MEDIA_PATH = newString("/sdcard/"); privateArrayList<HashMap<String, String>> songsList = newArrayList<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 =newFile(MEDIA_PATH); if(home.listFiles(newFileExtensionFilter()).length > 0) { for(File file : home.listFiles(newFileExtensionFilter())) { HashMap<String, String> song =newHashMap<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 * */ classFileExtensionFilterimplementsFilenameFilter { publicbooleanaccept(File dir, String name) { return(name.endsWith(".mp3") || name.endsWith(".MP3")); } } } |
8. 为PlayList写列表视图
为播放列表的列表视图创建一个新的活动类,叫做PlayListActivity.java ,PlayListActivity.java 这个类通过使用SongsManager.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; publicclassPlayListActivityextendsListActivity { // Songs list publicArrayList<HashMap<String, String>> songsList = newArrayList<HashMap<String, String>>(); @Override publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playlist); ArrayList<HashMap<String, String>> songsListData =newArrayList<HashMap<String, String>>(); SongsManager plm =newSongsManager(); // 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 =newSimpleAdapter(this, songsListData, R.layout.playlist_item,newString[] { "songTitle"},newint[] { 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,longid) { // getting listitem index intsongIndex = position; // Starting new intent Intent in =newIntent(getApplicationContext(), AndroidBuildingMusicPlayerActivity.class); // Sending songIndex to PlayerActivity in.putExtra("songIndex", songIndex); setResult(100, in); // Closing PlayListView finish(); } }); } } |
9. 辅助类的功能
创建一个新类,叫作Utilities.java,用来处理额外的工作像转换时间进度百分比,反之亦然。此外,它具有功能将毫秒定时器转换为时间字符串显示在播放器的seekbar上。
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,longtotalDuration){ 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,inttotalDuration) { intcurrentDuration = 0; totalDuration = (int) (totalDuration / 1000); currentDuration = (int) ((((double)progress) / 100) * totalDuration); // return current duration in milliseconds returncurrentDuration * 1000; } } |