如何在Android中使用ExFilePicker文件选择器?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
首先需要在build.gradle添加引用:
compile 'ru.bartwell:exfilepicker:2.1'
给出一个简单的代码例子:
package zhangfei.file;import android.content.Intent;import android.net.Uri;import android.os.Environment;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Toast;import java.io.File;import java.util.List;import ru.bartwell.exfilepicker.ExFilePicker;import ru.bartwell.exfilepicker.data.ExFilePickerResult;public class MainActivity extends AppCompatActivity { private AppCompatActivity mActivity; private final int EX_FILE_PICKER_RESULT = 0xfa01; private String startDirectory = null;// 记忆上一次访问的文件目录路径 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActivity = this; setContentView(R.layout.activity_main); findViewById(R.id.choose).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ExFilePicker exFilePicker = new ExFilePicker(); exFilePicker.setCanChooseOnlyOneItem(true);// 单选 exFilePicker.setQuitButtonEnabled(true); if (TextUtils.isEmpty(startDirectory)) { exFilePicker.setStartDirectory(Environment.getExternalStorageDirectory().getPath()); } else { exFilePicker.setStartDirectory(startDirectory); } exFilePicker.setChoiceType(ExFilePicker.ChoiceType.FILES); exFilePicker.start(mActivity, EX_FILE_PICKER_RESULT); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == EX_FILE_PICKER_RESULT) { ExFilePickerResult result = ExFilePickerResult.getFromIntent(data); if (result != null && result.getCount() > 0) { String path = result.getPath(); List<String> names = result.getNames(); for (int i = 0; i < names.size(); i++) { File f = new File(path, names.get(i)); try { Uri uri = Uri.fromFile(f); //这里获取了真实可用的文件资源 Toast.makeText(mActivity, "选择文件:" + uri.getPath(), Toast.LENGTH_SHORT) .show(); startDirectory = path; } catch (Exception e) { e.printStackTrace(); } } } } }}
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注编程网行业资讯频道,感谢您对编程网的支持。