从文件夹内的音频文件填充自定义列表视图

populate custom listview from audio files inside a folder

我正在尝试从文件夹中获取文件并使用自定义适配器根据文件名填充 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);
}

但问题是,它只是添加了第一项。 我不知道我应该在哪里循环添加所有内容。

您需要为循环中的项目创建单独的产品对象并将其添加到列表中,而不是在列表中创建单个 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 
}