接下来是自定义的适配器MusicAdapter
public class MusicAdapter extends BaseAdapter { private List<Music> listMusic; private Context context; public MusicAdapter(Context context,List<Music> listMusic){ this.context=context; this.listMusic=listMusic; } public void setListItem(List<Music> listMusic){ this.listMusic=listMusic; } @Override public int getCount() { // TODO Auto-generated method stub return listMusic.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return listMusic.get(arg0); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if(convertView==null){ convertView=LayoutInflater.from(context).inflate(R.layout.music_item, null); } Music m=listMusic.get(position); //音乐名 TextView textMusicName=(TextView) convertView.findViewById(R.id.music_item_name); textMusicName.setText(m.getName()); //歌手 TextView textMusicSinger=(TextView) convertView.findViewById(R.id.music_item_singer); textMusicSinger.setText(m.getSinger()); //持续时间 TextView textMusicTime=(TextView) convertView.findViewById(R.id.music_item_time); textMusicTime.setText(toTime((int)m.getTime())); return convertView; } /** * 时间格式转换 * @param time * @return */ public String toTime(int time) { time /= 1000; int minute = time / 60; int hour = minute / 60; int second = time % 60; minute %= 60; return String.format("%02d:%02d", minute, second); } }
时间格式的转换是我从网上找到的,直接调用toTime方法能得到格式化后的时间了。最后是在ListActivity添加适配器:
public class ListActivity extends Activity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.listmusic); listView= (ListView) this.findViewById(R.id.listAllMusic); List<Music> listMusic=MusicList.getMusicData(getApplicationContext()); MusicAdapter adapter=new MusicAdapter(this, listMusic); listView.setAdapter(adapter); } }
这样音乐文件就会加载上来了,看看效果吧: