2017-09-16 51 views
1

我试图从文件夹获取文件并使用自定义适配器基于文件的名称填充recyclerview。从文件夹中的音频文件填充自定义列表视图

这是我正在做它:

onBindViewHolder

Product m = dataList.get(position); 
    //title 
    holder.title.setText(m.getTitle()); 

和:

void popList() { 
    Product product = new Product(); 
    File dir = new File(mainFolder);//path of files 
    File[] filelist = dir.listFiles(); 
    String[] nameOfFiles = new String[filelist.length]; 
    for (int i = 0; i < nameOfFiles.length; i++) { 
     nameOfFiles[i] = filelist[i].getName(); 
     product.setTitle(nameOfFiles[i]); 
    } 
    songList.add(product); 
} 

但问题是,它只是增加了第一个项目。 我无法弄清楚我应该在哪里循环添加它。

回答

3

您需要在循环项目创建单独的产品对象,并将其添加到列表,而不是建立在列表中的单个Product对象将举行最后一组数据

void popList() { 
    Product product ; 
    File dir = new File(mainFolder);//path of files 
    File[] filelist = dir.listFiles(); 
    String[] nameOfFiles = new String[filelist.length]; 
    for (int i = 0; i < nameOfFiles.length; i++) { 
     // create product 
     product = new Product(); 
     nameOfFiles[i] = filelist[i].getName(); 
     product.setTitle(nameOfFiles[i]); 
     // add it to list 
     songList.add(product); 
    } 
} 

您的代码穿行

void popList() { 
    Product product = new Product(); // one object 
    // ..code 
    for (int i = 0; i < nameOfFiles.length; i++) { 
     nameOfFiles[i] = filelist[i].getName(); 
     product.setTitle(nameOfFiles[i]); // at the end of loop set last file name to object 
    } 
    songList.add(product); // one object in the list , end of story 
} 
相关问题