在我的应用程序中,我点击了一个按钮,该按钮将打开一个文件选择器,在选择文件后,我可以在 onActivityResult() 中获取所选文件的 uri。但是,我发现的问题是我总是必须选择多个文件来获取 uri 路径。在单个文件选择的情况下,onActivityResult() 中不返回 uri 数据。下面我发布我的代码。请看一看。
Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setDataAndType(uri, "resource/folder");
chooseFile.putExtra(Intent.EXTRA_STREAM, uri);
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
//chooseFile.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(chooseFile, PICKFILE_RESULT_CODE);
活动结果():
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
if (data != null) {
ClipData clipData = data.getClipData();
if (clipData != null) {
Log.d("attachmentnumber",clipData.getItemCount()+alst_attachmentNames.size()+"");
if(clipData.getItemCount()>5 || (clipData.getItemCount()+alst_attachmentNames.size())>5 )
{
Toast.makeText(myContext,"attachment of 5 or less than 5 items are allowed", Toast.LENGTH_SHORT).show();
}
else
{
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
Uri uri = item.getUri();
//In case you need image's absolute path
try {
String path= getFilePath(getActivity(), uri);
alst_attachmentPaths.add(path);
alst_attachmentNames.add(path.substring(path.lastIndexOf("/")+1));
Log.d("pathValues", path);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
LinearLayoutManager layoutManager=
new LinearLayoutManager(myContext, LinearLayoutManager.HORIZONTAL, false);
RecyclerView.Adapter attachmentAdapter = new attachmentAdapter(myContext, alst_attachmentNames);
rvw_attachmentList.setLayoutManager(layoutManager);
rvw_attachmentList.setAdapter(attachmentAdapter);
Log.d("arraylistValues", Arrays.toString(alst_attachmentNames.toArray())+"/n"+
Arrays.toString(alst_attachmentPaths.toArray()));
}
}
}