【问题标题】:populate custom listview from audio files inside a folder从文件夹内的音频文件填充自定义列表视图
【发布时间】:2017-09-16 15:59:11
【问题描述】:

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

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

【问题讨论】:

    标签: android listview arraylist custom-adapter


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多