我正在尝试在片段内的自定义列表视图中填充mp3文件,而片段又是viewpager的一部分。以下是我想要放置列表视图的片段代码:
public class FragmentSongs extends Fragment {
private static final String Sd_Path=new String("/sdcard/");
private MediaPlayer mp =new MediaPlayer();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
ListView SngList = (ListView) view.findViewById(R.id.SongList);
SongDetails Detail = null ;
Context _c = null ;
ArrayList<SongDetails> Songinfo;
// AdapterView.AdapterContextMenuInfo info;
Songinfo = new ArrayList<SongDetails>();
File f=new File("/system/");
File[] files = f.listFiles(new Mp3Filter());
if( files.length>0)
{
for(int i=0; i<files.length; i++)
{Detail.setIcon(R.drawable.ic_launcher);
Detail.setSong(files[i].getName());
Detail.setArtist(files[i].getName());
Detail.setAlbum(files[i].getName());
Songinfo.add(Detail);
SngList.setAdapter(new CustomAdapter(Songinfo ));
}
}
else if (files.length == 0)
return null;
return view;
}
}
class Mp3Filter implements FilenameFilter{
public boolean accept(File dir,String name)
{
return (name.endsWith(".rc"))|| (name.endsWith(".Mp3")) ||
(name.endsWith(".MP3"));//searching for the files
}
}
答案 0 :(得分:2)
if( files.length>0) {
for(int i=0; i<files.length; i++) {
SongDetails detail = new SongDetails();
detail.setIcon(R.drawable.ic_launcher);
detail.setSong(files[i].getName());
detail.setArtist(files[i].getName());
detail.setAlbum(files[i].getName());
Songinfo.add(detail);
}
SngList.setAdapter(new CustomAdapter(Songinfo ));
}
在for循环中,有两件事是错误的。您在每次迭代时创建的第一个新CustomAdapter
。当循环用完时,Yoph应该创建并设置它。第二个错误是你在每次迭代时都会覆盖Detail的值。您应该在每次迭代时创建一个新的Detail
对象