Метод launch
Метод launch у
ActivityResultLauncher
принимает аргумент, который ждёт контракт,
и показывает UI.
Для
RequestPermission
это строка разрешения,
для
PickVisualMedia -
запрос выбора медиа.
Ответ придёт в лямбду onResult
у rememberLauncherForActivityResult.
Синтаксис
launcher.launch(input)
Параметры
| Параметр | Описание |
|---|---|
input |
Вход контракта. Тип зависит от ActivityResultContract, с которым создали launcher. |
Пример
Давайте вызовем launch для камеры:
import android.Manifest
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
var label by remember { mutableStateOf("abcde") }
val launcher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission(),
) { granted ->
label = if (granted) "12345" else "abcde"
}
Button(onClick = {
launcher.launch(Manifest.permission.CAMERA)
}) {
Text(text = "abcde")
}
Text(text = label)
}
}
}
На экране launch откроет диалог разрешения, а текст сменится после ответа пользователя.
Смотрите также
-
класс
ActivityResultLauncher,
у которого объявлен launch -
класс
RequestPermission,
куда launch передаёт имя permission -
метод
shouldShowRequestPermissionRationale,
который вызывают до launch -
функция
rememberLauncherForActivityResult,
которая регистрирует launcher