如何在 ListView 中显示 SD 卡上的文件? [英] How to display files on the SD card in a ListView?

查看:35
本文介绍了如何在 ListView 中显示 SD 卡上的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个按钮,单击该按钮后将转到使用 ListView 显示 SD 卡中所有媒体文件的类.

I would like to create a button that when clicked will go to a class that displays all media files from an SD card using a ListView.

从列表中选择后,它会将选择的文件名返回给主类.如果返回的文件是图像文件,它将显示在 ImageView 中,如果返回的文件是音频文件,它只会显示一个图标.

After selecting from the list it will then return the filename selected to the main class. IF the returned file is an image file, it will be displayed in an ImageView and if the returned file is an audio file, it'll just display an icon.

推荐答案

向您的程序添加方法 GetFiles().调用它以获取所有文件的 ArrayList<>.然后您可以使用它来填充您的 listview.您需要提供字符串参数 DirectoryPath.

Add a Method GetFiles() to your program. Call it to get an ArrayList<> of all the files. You can then use it to populate your listview. You need to provide String argument DirectoryPath.

功能:

public ArrayList<String> GetFiles(String DirectoryPath) {
    ArrayList<String> MyFiles = new ArrayList<String>();
    File f = new File(DirectoryPath);

    f.mkdirs();
    File[] files = f.listFiles();
    if (files.length == 0)
        return null;
    else {
        for (int i=0; i<files.length; i++) 
            MyFiles.add(files[i].getName());
    }

    return MyFiles;
}

使用示例:

@Override
public void onCreate() {
// Other Code

    ListView lv;
    ArrayList<String> FilesInFolder = GetFiles("/sdcard/somefolder");
    lv = (ListView)findViewById(R.id.filelist);

    lv.setAdapter(new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, FilesInFolder));

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // Clicking on items
         }
    });
}

确保外部存储可读: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

根据名称/扩展名过滤文件: 如何访问 sdcard 并返回和数组与特定格式的文件?

这篇关于如何在 ListView 中显示 SD 卡上的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆