想做一个音乐播放器,首先当然要有播放列表啊,通过查资料,暂时先做了个获取SD卡里所有MP3文件名称的小Demo,效果图如下:
1.资源管理器预览,主要是1个Activity和2个布局文件:
2.然后就是代码了
class="code_img_closed" src="/Upload/Images/2013110423/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('850ba7d4-ee4d-47ff-bfc5-d449b71d0489',event)" src="/Upload/Images/2013110423/2B1B950FA3DF188F.gif" alt="" />
package com.example.sdtxt; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends Activity { private ListView mListView; private ArrayList name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mListView = (ListView) findViewById(R.id.mListView); name = new ArrayList(); if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File path = Environment.getExternalStorageDirectory(); // 获得SD卡路径 File[] files = path.listFiles();// 读取 getFileName(files); } SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, name, R.layout.sd_list, new String[] { "Name" }, new int[] { R.id.tc_fileName }); mListView.setAdapter(adapter); } private void getFileName(File[] files) { if (files != null)// 先判断目录是否为空,否则会报空指针 { for (File file : files) { if (file.isDirectory()) { getFileName(file.listFiles()); } else { String fileName = file.getName(); if (fileName.endsWith(".mp3")) { HashMap map = new HashMap(); String s = fileName.substring(0, fileName.lastIndexOf(".")); map.put("Name", fileName.substring(0,fileName.lastIndexOf("."))); name.add(map); } } } } } }MainActivity.java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ListView android:id="@+id/mListView" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </RelativeLayout>activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:id="@+id/tv_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:text="音乐文件:" /> <TextView android:id="@+id/tc_fileName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout>sd_list.xml
3.最后注意添上权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
源代码下载