使用 SAF 从 Uri 获取文件夹名称

Get Folder Name from Uri using SAF

我正在使用允许用户 select directory/folder 的 SAF,然后我想在 selected 后在 Textview 中显示它的名称。我使用下面的代码来启动意图。

  Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                startActivityForResult(intent, 1);

以下代码用于 onActivityResult

  if (resultCode == RESULT_OK && requestCode == 1) {
    DocumentFile documentFile = DocumentFile.fromTreeUri(this, uriTree);

            textInfo.append(documentFile .getName() + "\n");

        }

根据指南更改了问题,现在返回文件夹名称。

使用 DocumentFile.fromTreeUri() 在树 Uri 上获得一个 DocumentFile,您将在 onActivityResult() 中获得。然后,在 DocumentFile 上调用 getName() 以获取与该树关联的显示名称。