android – 显示SD卡上的所有音乐
作者:互联网
我正在使用此页面的代码:
http://z4android.blogspot.com/2011/06/displaying-list-of-music-files-stored.html
代码正在运行,但并不太好.
当我尝试向下滚动时,ListView会不断重复列表中的歌曲.
我一直在寻找一些替代代码,但我没有找到任何代码.
谢谢你的帮助.
解决方法:
我不完全确定是什么原因导致你提到的问题,但试试这个代码.
private MediaPlayer mMediaPlayer;
private String[] mMusicList;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.listView1);
mMusicList = getMusic();
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
try {
playSong(mMusicList[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getMusic() {
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.DISPLAY_NAME }, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(0);
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
path = extStorageDirectory + File.separator + path;
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
标签:android,listview,sd-card 来源: https://codeday.me/bug/20190930/1835198.html