可扩展的文件选择器NoNonsense-FilePicker

下面的内容主要来自于该项目github页面的翻译:NoNonsense-FilePicker项目介绍:http://jcodecraeer.com/a/opensource/2014/1012/1753.html

NoNonsense-FilePicker有如下特点:

1.可扩展以适应不同的数据源。

2.支持多选。

3.可以选择目录或者是文件。

4.可以在选择器中新建目录。

NoNonsense-FilePicker不只是另外一个文件选择器而已

我需要的是这样一个文件选择器:
1.容易扩展,文件来源既可以是本地sdcard,也可以是来自云端的dropboxapi。
2.可以在选择器中创建目录。
本项目具备上述的两个要求,同时很好的适配了平板和手机两种UI效果。项目的核心是在一个abstract 类中,因此你可以很方便的继承以实现自己需要的选择器。
项目本身已经包含了一个能够选择本地sdcard文件的实现,但你完全可以扩展实现一个文件列表来源于云端的选择器,比如Dropbox, ftp,ssh等。

选择器是基于activity,在屏幕较小的设备上全屏显示,而在较大的屏幕上则显示成dialog的方式,这个特性是系统主题中做到的,因此为activity选择一个正确的主题至关重要。

使用说明:

该库的核心思想是做到可扩展,但是你只是想选择sdcard中的文件,只需阅读关于如何使用sdcard文件选择器就可以了。

首选需要加上文件访问权限:

1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

将选择器的app注册到AndroidManifest.xml

1
2
3
4
5
6
7
8
9
<activity
android:name="com.nononsenseapps.filepicker.FilePickerActivity"
android:label="@string/app_name"
android:theme="@style/FilePicker.Theme">
<intent-filter>
<action android:name="android.intent.action.GET_CONTENT"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>

在java代码中调用选择器:

1
2
3
4
5
6
7
8
9
// This always works
Intent i = newIntent(context, FilePickerActivity.class);
// This works if you defined the intent filter
// Intent i = new Intent(Intent.ACTION_GET_CONTENT);
// Set these depending on your use case. These are the defaults.
i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false);
i.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_FILE);
startActivityForResult(i, FILE_CODE);

获取选择的返回值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) {
if(data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {
// For JellyBean and above
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ClipData clip = data.getClipData();
if(clip != null) {
for(int i = 0; i < clip.getItemCount(); i++) {
Uri uri = clip.getItemAt(i).getUri();
// Do something with the URI
}
}
// For Ice Cream Sandwich
} else{
ArrayList<String> paths = data.getStringArrayListExtra
(FilePickerActivity.EXTRA_PATHS);
if(paths != null) {
for(String path: paths) {
Uri uri = Uri.parse(path);
// Do something with the URI
}
}
}
} else{
Uri uri = data.getData();
// Do something with the URI
}
}
}