다음 함수가 파일을 대화상자를 불러오는 함수이다.
val pickPictureLauncher = rememberLauncherForActivityResult( ActivityResultContracts.GetContent()) { hwpUri -> if (hwpUri != null) { // Update the state with the Uri } }
다음의 방식으로 호출한다.
pickPictureLauncher.launch("image/*")
문서는 OpenDocument()로 호출한다.
val pickPictureLauncher = rememberLauncherForActivityResult( ActivityResultContracts.OpenDocument()) { hwpUri -> if (hwpUri != null) { // Update the state with the Uri } }
다음과 같이 하면 GetContent()에 mime 제한자를 멀티플로 변경할 수 있다.
class GetContentWithMultiFilter:ActivityResultContracts.GetContent() { override fun createIntent(context: Context, input:String): Intent { val inputArray = input.split(";").toTypedArray() val myIntent = super.createIntent(context, arrayOf("*/*")) myIntent.putExtra(Intent.EXTRA_MIME_TYPES, inputArray) return myIntent } }
다음은 실제 사용례이다.
val pickPictureLauncher = rememberLauncherForActivityResult( ActivityResultContracts.OpenDocument()) { hwpUri -> if (hwpUri != null) { // Update the state with the Uri name = hwpUri.path.toString() val file: File = File(hwpUri.getPath()) //create path from uri val split = file.path.split(":".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray() //split the path. fname = split[1] //assign it to a string(your choice). } } Column (modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally){ Image(painter = painterResource(id = imageResource), contentDescription = result.toString()) Spacer(modifier = Modifier.height(16.dp)) Text(text = name, fontSize = 24.sp, modifier = Modifier .fillMaxWidth() .wrapContentWidth(align = Alignment.CenterHorizontally) .padding(top = 16.dp)) Text(text = fname, fontSize = 24.sp, modifier = Modifier .fillMaxWidth() .wrapContentWidth(align = Alignment.CenterHorizontally) .padding(top = 16.dp)) Button(onClick = { pickPictureLauncher.launch(arrayOf("application/msword", "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")) } ) { Text(text = stringResource(R.string.fileopen)) } }