androidx.activity.compose

Classes

ManagedActivityResultLauncher

A launcher for a previously-prepared call to start the process of executing an ActivityResultContract.

Objects

Top-level functions summary

Unit
@Composable
BackHandler(enabled: Boolean, onBack: () -> Unit)

An effect for handling presses of the system back button.

Unit
@Composable
PredictiveBackHandler(
    enabled: Boolean,
    onBack: suspend (progress: Flow<BackEventCompat>) -> Unit
)

An effect for handling predictive system back gestures.

Unit

Calls Activity.reportFullyDrawn after this composition is completed.

Unit
@Composable
ReportDrawnAfter(block: suspend () -> Unit)

Adds block to the methods that must complete prior to Activity.reportFullyDrawn being called.

Unit

Adds predicate to the conditions that must be met prior to Activity.reportFullyDrawn being called.

ManagedActivityResultLauncher<I, O>
@Composable
<I : Any?, O : Any?> rememberLauncherForActivityResult(
    contract: ActivityResultContract<I, O>,
    onResult: (O) -> Unit
)

Register a request to start an activity for result, designated by the given ActivityResultContract.

Extension functions summary

Unit
ComponentActivity.setContent(
    parent: CompositionContext?,
    content: @Composable () -> Unit
)

Composes the given composable into the given activity.

Top-level functions

BackHandler

@Composable
fun BackHandler(enabled: Boolean = true, onBack: () -> Unit): Unit

An effect for handling presses of the system back button.

Calling this in your composable adds the given lambda to the OnBackPressedDispatcher of the LocalOnBackPressedDispatcherOwner.

If this is called by nested composables, if enabled, the inner most composable will consume the call to system back and invoke its lambda. The call will continue to propagate up until it finds an enabled BackHandler.

import androidx.activity.compose.BackHandler
import androidx.compose.material.TextField
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember

var text by remember { mutableStateOf("") }

TextField(
    value = text,
    onValueChange = { text = it }
)

BackHandler(text.isNotEmpty()) {
    // handle back event
}
Parameters
enabled: Boolean = true

if this BackHandler should be enabled

onBack: () -> Unit

the action invoked by pressing the system back

PredictiveBackHandler

@Composable
fun PredictiveBackHandler(
    enabled: Boolean = true,
    onBack: suspend (progress: Flow<BackEventCompat>) -> Unit
): Unit

An effect for handling predictive system back gestures.

Calling this in your composable adds the given lambda to the OnBackPressedDispatcher of the LocalOnBackPressedDispatcherOwner. The lambda passes in a Flow where each BackEventCompat reflects the progress of current gesture back. The lambda content should follow this structure:

PredictiveBackHandler { progress: Flow<BackEventCompat> ->
// code for gesture back started
try {
progress.collect { backevent ->
// code for progress
}
// code for completion
} catch (e: CancellationException) {
// code for cancellation
}
}

If this is called by nested composables, if enabled, the inner most composable will consume the call to system back and invoke its lambda. The call will continue to propagate up until it finds an enabled BackHandler.

import androidx.activity.compose.PredictiveBackHandler
import androidx.compose.material.TextField
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember

var text by remember { mutableStateOf("") }

TextField(
    value = text,
    onValueChange = { text = it }
)

PredictiveBackHandler(text.isNotEmpty()) { progress: Flow<BackEventCompat> ->
    callback.preparePop()
    try {
        progress.collect { backEvent ->
            callback.updateProgress(backEvent.progress)
        }
        callback.popBackStack()
    } catch (e: CancellationException) {
        callback.cancelPop()
    }
}
Parameters
enabled: Boolean = true

if this BackHandler should be enabled, true by default

onBack: suspend (progress: Flow<BackEventCompat>) -> Unit

the action invoked by back gesture

ReportDrawn

@Composable
fun ReportDrawn(): Unit

Calls Activity.reportFullyDrawn after this composition is completed.

The Activity used is extracted from the LocalView's context.

import androidx.activity.compose.ReportDrawn
import androidx.compose.material.Text

ReportDrawn()
Text("Hello World")

ReportDrawnAfter

@Composable
fun ReportDrawnAfter(block: suspend () -> Unit): Unit

Adds block to the methods that must complete prior to Activity.reportFullyDrawn being called.

The Activity used is extracted from the LocalView's context.

After Activity.reportFullyDrawn has been called, block will not be called again, even on recomposition.

import androidx.activity.compose.ReportDrawnAfter
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.remember

val lazyListState = remember { LazyListState() }
ReportDrawnAfter {
    lazyListState.animateScrollToItem(10)
}

ReportDrawnWhen

@Composable
fun ReportDrawnWhen(predicate: () -> Boolean): Unit

Adds predicate to the conditions that must be met prior to Activity.reportFullyDrawn being called.

The Activity used is extracted from the LocalView's context.

import androidx.activity.compose.ReportDrawnWhen
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember

var contentComposed by remember { mutableStateOf(false) }
LazyColumn(modifier = Modifier.fillMaxSize()) {
    items(100) {
        contentComposed = true
        Text("Hello World $it")
    }
}
ReportDrawnWhen { contentComposed }

rememberLauncherForActivityResult

@Composable
fun <I : Any?, O : Any?> rememberLauncherForActivityResult(
    contract: ActivityResultContract<I, O>,
    onResult: (O) -> Unit
): ManagedActivityResultLauncher<I, O>

Register a request to start an activity for result, designated by the given ActivityResultContract.

This creates a record in the registry associated with this caller, managing request code, as well as conversions to/from Intent under the hood.

This must be called unconditionally, as part of initialization path.

You should not call ActivityResultLauncher.unregister on the returned ActivityResultLauncher. Attempting to do so will result in an IllegalStateException.

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.launch
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.asImageBitmap

val result = remember { mutableStateOf<Bitmap?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicturePreview()) {
    result.value = it
}

Button(onClick = { launcher.launch() }) {
    Text(text = "Take a picture")
}

result.value?.let { image ->
    Image(image.asImageBitmap(), null, modifier = Modifier.fillMaxWidth())
}
Parameters
contract: ActivityResultContract<I, O>

the contract, specifying conversions to/from Intents

onResult: (O) -> Unit

the callback to be called on the main thread when activity result is available

Returns
ManagedActivityResultLauncher<I, O>

the launcher that can be used to start the activity.

Extension functions

setContent

fun ComponentActivity.setContent(
    parent: CompositionContext? = null,
    content: @Composable () -> Unit
): Unit

Composes the given composable into the given activity. The content will become the root view of the given activity.

This is roughly equivalent to calling ComponentActivity.setContentView with a ComposeView i.e.:

setContentView(
ComposeView(this).apply {
setContent {
MyComposableContent()
}
}
)
Parameters
parent: CompositionContext? = null

The parent composition reference to coordinate scheduling of composition updates

content: @Composable () -> Unit

A @Composable function declaring the UI contents