android中文件选择器的库看了好几种,最后选择了materialfilepicker,因为其他都报诡异的错误,我这里用的androidx环境,我相信在v4中materialfilepicker应该表现也会很不错。
按照步骤进行:
步骤1:添加库
repositories {
jcenter()
}
dependencies {
implementation 'com.nbsp:materialfilepicker:1.9.1'
}
步骤二,添加文件打开管理器代码
更多打开方式可以进一步学习。
private int REQUESTCODE_FROM_ACTIVITY=1;
private void fileToHex() {
new MaterialFilePicker().withActivity(this)
.withCloseMenu(true)
// Entry point path (user will start from it)
//.withPath(alarmsFolder.absolutePath)
// Root path (user won't be able to come higher than it)
// .withRootPath(externalStorage.absolutePath)
// Showing hidden files
.withHiddenFiles(true)
// Want to choose only jpg images
.withFilter(Pattern.compile(".*\\.(hex|Hex)$"))
// Don't apply filter to directories names
.withFilterDirectories(false)
.withTitle("Sample title")
.withRequestCode(REQUESTCODE_FROM_ACTIVITY)//必须添加
.start();
}
第三步,添加回调处理:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUESTCODE_FROM_ACTIVITY && resultCode == RESULT_OK) {
String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
// Do anything with file
}
}