2023年7月15日土曜日

ActivityResultContracts.CreateDocument に指定する mimeType には * を使ってはいけない

mimeType に "text/*"、ファイル名に "sample.csv" を指定した場合、ファイル名が重複したときの "(1)" が拡張子の後につけられてしまう。
  1. @Composable  
  2. fun CreateDocumentSample() {  
  3.     val createDocumentLauncher =  
  4.         rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/*")) {  
  5.             if (it != null) {  
  6.                 ...  
  7.             }  
  8.         }  
  9.   
  10.     Button(  
  11.         onClick = {  
  12.             createDocumentLauncher.launch("sample.csv")  
  13.         }  
  14.     ) {  
  15.         Text("Click")  
  16.     }  
  17. }  


mimeType を "text/csv" にし、ファイル名を "sample.csv" や "sample" にした場合、ファイル名が重複したときの "(1)" が拡張子の前になる。
  1. @Composable  
  2. fun CreateDocumentSample() {  
  3.     val createDocumentLauncher =  
  4.         rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/csv")) {  
  5.             if (it != null) {  
  6.                 ...  
  7.             }  
  8.         }  
  9.   
  10.     Button(  
  11.         onClick = {  
  12.             createDocumentLauncher.launch("sample.csv")  
  13.         }  
  14.     ) {  
  15.         Text("Click")  
  16.     }  
  17. }  
  1. @Composable  
  2. fun CreateDocumentSample() {  
  3.     val createDocumentLauncher =  
  4.         rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/csv")) {  
  5.             if (it != null) {  
  6.                 ...  
  7.             }  
  8.         }  
  9.   
  10.     Button(  
  11.         onClick = {  
  12.             createDocumentLauncher.launch("sample")  
  13.         }  
  14.     ) {  
  15.         Text("Click")  
  16.     }  
  17. }  


名前についている拡張子が mimeType と異なる場合その部分は拡張子とは認識されず、mimeType に基づいた拡張子がつきます。

以下では mimeType が "text/plain" でファイル名が "sample.csv" なので ".csv" は拡張子とは認識されず、実際のファイル名は "sample.csv.txt" になります。
  1. @Composable  
  2. fun CreateDocumentSample() {  
  3.     val createDocumentLauncher =  
  4.         rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) {  
  5.             if (it != null) {  
  6.                 ...  
  7.             }  
  8.         }  
  9.   
  10.     Button(  
  11.         onClick = {  
  12.             createDocumentLauncher.launch("sample.csv")  
  13.         }  
  14.     ) {  
  15.         Text("Click")  
  16.     }  
  17. }