如何使用Android Studio创建文件选择器对话框

时间:2016-07-03 13:57:48

标签: android file dialog

今天我要创建一个File Chosser,在选择文件后,它会打开一个带有所选文件路径的Normal Dialog。我试着做这个项目,但我不明白我该怎么做。

2 个答案:

答案 0 :(得分:0)

您可以查看:aFileChooser

代码:

清单中的活动

<activity
android:name="com.ipaulpro.afilechooser.FileChooserActivity"
android:icon="@drawable/ic_chooser"
android:enabled="@bool/use_activity"
android:exported="true"
android:label="@string/choose_file" >
<intent-filter>
    <action android:name="android.intent.action.GET_CONTENT" />

    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.OPENABLE" />

    <data android:mimeType="*/*" />
</intent-filter>

Java代码

private static final int REQUEST_CHOOSER = 1234;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Create the ACTION_GET_CONTENT Intent
Intent getContentIntent = FileUtils.createGetContentIntent();

Intent intent = Intent.createChooser(getContentIntent, "Select a file");
startActivityForResult(intent, REQUEST_CHOOSER);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent     data) {
switch (requestCode) {
    case REQUEST_CHOOSER:   
        if (resultCode == RESULT_OK) {

            final Uri uri = data.getData();

            // Get the File path from the Uri
            String path = FileUtils.getPath(this, uri);

            // Alternatively, use FileUtils.getFile(Context, Uri)
            if (path != null && FileUtils.isLocal(path)) {
                File file = new File(path);
            }
        }
        break;
 }
}

如果您想使用存储访问框架(API 19+),请在<application>:

中添加Ian Lake的LocalStorageProvider(包含在此库中)
<provider
    android:name="com.ianhanniballake.localstorage.LocalStorageProvider"
    android:authorities="com.ianhanniballake.localstorage.documents"
    android:enabled="@bool/use_provider"
    android:exported="true"
    android:grantUriPermissions="true"
    android:permission="android.permission.MANAGE_DOCUMENTS" >
        <intent-filter>
            <action android:name="android.content.action.DOCUMENTS_PROVIDER" />
        </intent-filter>
</provider>

答案 1 :(得分:-2)

dependencies {
    compile 'org.apache.commons:commons-io:1.3.2'
}