我想做一个文件浏览器,它可以做两件事: 1) 允许用户浏览并选择目录 2)允许用户浏览其sdcard上的所有文件
我一直在寻找教程,但似乎找不到任何教程? 有人可以帮助我解释我的代码需要做什么才能拥有一个简单的文件浏览器,或者为我提供一个教程/源代码的链接吗?
请,谢谢!
最佳答案
如果您实际上对学习编写自己的代码更感兴趣,我建议您仔细阅读 File类文档。这就是你要做大部分工作的地方。
对于适用于 Android 的 SD 卡/其他外部存储,您需要先使用 Environment 进行检查以确保外部存储已安装且可用,然后再尝试读取它。类:
String extState = Environment.getExternalStorageState();
//you may also want to add (...|| Environment.MEDIA_MOUNTED_READ_ONLY)
//if you are only interested in reading the filesystem
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
//do your file work here
}
一旦您确定了外部存储的正确状态,一个简单的开始方法是使用 File 的 listFiles() 方法,如下所示:
//there is also getRootDirectory(), getDataDirectory(), etc. in the docs
File sd = Environment.getExternalStorageDirectory();
//This will return an array with all the Files (directories and files)
//in the external storage folder
File[] sdDirList = sd.listFiles();
然后您可以开始使用 FileFilters 来缩小结果范围:
FileFilter filterDirectoriesOnly = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] sdDirectories = sd.listFiles(filterDirectoriesOnly);
从那里开始,只需通读文档以找到您想要用它做的事情的类型,然后您就可以将它们绑定(bind)到列表适配器等中。
希望这会有所帮助!
关于安卓编程: Where To Start For Creating A Simple File Browser?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4108881/