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

10-07 19:06
查看更多