### Small Top App Bar Example Source: https://developer.android.com/develop/ui/compose/components/app-bars A basic small top app bar with a title. This implementation does not react to scrolling. ```kotlin import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color @Composable fun SmallTopAppBarExample() { Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text("Small Top App Bar") } ) }, ) { innerPadding -> ScrollContent(innerPadding) } } @Composable fun ScrollContent(padding: PaddingValues) { // Content that scrolls } ``` -------------------------------- ### Example Usage of MomentaryIconButton Source: https://developer.android.com/develop/ui/compose/components/icon-button Demonstrates how to use the `MomentaryIconButton` to create UI elements that increment or decrement a counter value while the button is pressed and held. This example showcases two buttons controlling a shared state. ```kotlin @Preview() @Composable fun MomentaryIconButtonExample() { var pressedCount by remember { mutableIntStateOf(0) } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { MomentaryIconButton( unselectedImage = R.drawable.fast_rewind, selectedImage = R.drawable.fast_rewind_filled, stepDelay = 100L, onClick = { pressedCount -= 1 }, contentDescription = "Decrease count button" ) Spacer(modifier = Modifier) Text("advanced by $pressedCount frames") Spacer(modifier = Modifier) MomentaryIconButton( unselectedImage = R.drawable.fast_forward, selectedImage = R.drawable.fast_forward_filled, contentDescription = "Increase count button", stepDelay = 100L, onClick = { pressedCount += 1 } ) } } IconButton.kt ``` -------------------------------- ### Create a Detailed Navigation Drawer - Compose Source: https://developer.android.com/develop/ui/compose/components/drawer Implement a navigation drawer with sections, dividers, and navigation items. This example uses `ModalNavigationDrawer` and `ModalDrawerSheet` to structure the drawer content. ```kotlin @Composable fun DetailedDrawerExample( content: @Composable (PaddingValues) -> Unit ) { val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) val scope = rememberCoroutineScope() ModalNavigationDrawer( drawerContent = { ModalDrawerSheet { Column( modifier = Modifier.padding(horizontal = 16.dp) .verticalScroll(rememberScrollState()) ) { Spacer(Modifier.height(12.dp)) Text("Drawer Title", modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.titleLarge) HorizontalDivider() Text("Section 1", modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.titleMedium) NavigationDrawerItem( label = { Text("Item 1") }, selected = false, onClick = { /* Handle click */ } ) NavigationDrawerItem( label = { Text("Item 2") }, selected = false, onClick = { /* Handle click */ } ) HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) Text("Section 2", modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.titleMedium) NavigationDrawerItem( label = { Text("Settings") }, selected = false, icon = { Icon(Icons.Outlined.Settings, contentDescription = null) }, badge = { Text("20") }, // Placeholder onClick = { /* Handle click */ } ) NavigationDrawerItem( label = { Text("Help and feedback") }, selected = false, icon = { Icon(Icons.AutoMirrored.Outlined.Help, contentDescription = null) }, onClick = { /* Handle click */ }, ) Spacer(Modifier.height(12.dp)) } } }, drawerState = drawerState ) { Scaffold( topBar = { TopAppBar( title = { Text("Navigation Drawer Example") }, navigationIcon = { IconButton(onClick = { scope.launch { if (drawerState.isClosed) { drawerState.open() } else { drawerState.close() } } }) { Icon(Icons.Default.Menu, contentDescription = "Menu") } } ) } ) { content(it) } } } ``` -------------------------------- ### Complete Scaffold Implementation Source: https://developer.android.com/develop/ui/compose/components/scaffold Use this example to create a screen with a top app bar, bottom app bar, and floating action button. Ensure you have the necessary Material Design dependencies imported. ```kotlin import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.* // Assuming Material 3 components are used import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun ScaffoldExample() { var presses by remember { mutableIntStateOf(0) } Scaffold( topBar = { TopAppBar( colors = topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text("Top app bar") } ) }, bottomBar = { BottomAppBar( containerColor = MaterialTheme.colorScheme.primaryContainer, contentColor = MaterialTheme.colorScheme.primary, ) { Text( modifier = Modifier .fillMaxWidth(), textAlign = TextAlign.Center, text = "Bottom app bar", ) } }, floatingActionButton = { FloatingActionButton(onClick = { presses++ }) { Icon(Icons.Default.Add, contentDescription = "Add") } } ) { Column( modifier = Modifier .padding(it), verticalArrangement = Arrangement.spacedBy(16.dp), ) { Text( modifier = Modifier.padding(8.dp), text = """ This is an example of a scaffold. It uses the Scaffold composable's parameters to create a screen with a simple top app bar, bottom app bar, and floating action button. It also contains some basic inner content, such as this text. You have pressed the floating action button $presses times. """.trimIndent(), ) } } } ``` -------------------------------- ### Horizontal Divider Example Source: https://developer.android.com/develop/ui/compose/components/divider Demonstrates how to use HorizontalDivider to separate items in a Column. Uses the thickness parameter to control the height of the divider. ```kotlin import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.unit.dp @Composable fun HorizontalDividerExample() { Column( verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text("First item in list") HorizontalDivider(thickness = 2.dp) Text("Second item in list") } } ``` -------------------------------- ### Outlined Card Example Source: https://developer.android.com/develop/ui/compose/components/card Use the dedicated `OutlinedCard` composable for cards with a border. This example demonstrates setting container color, border, and size. ```kotlin @Composable fun OutlinedCardExample() { OutlinedCard( colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surface, ), border = BorderStroke(1.dp, Color.Black), modifier = Modifier .size(width = 240.dp, height = 100.dp) ) { Text( text = "Outlined", modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) } } Card.kt ``` -------------------------------- ### Medium Top App Bar Example Source: https://developer.android.com/develop/ui/compose/components/app-bars Use `MediumTopAppBar` to display the title below icons. This example uses `enterAlwaysScrollBehavior` for scroll effects. ```kotlin import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MediumTopAppBar import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.ui.input.nestedscroll.nestedScroll @OptIn(ExperimentalMaterial3Api::class) @Composable fun MediumTopAppBarExample() { val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(rememberTopAppBarState()) Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { MediumTopAppBar( colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text( "Medium Top App Bar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* do something */ }) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Localized description" ) } }, actions = { IconButton(onClick = { /* do something */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, scrollBehavior = scrollBehavior ) }, ) { ScrollContent(it) } } @Composable fun ScrollContent(padding: androidx.compose.foundation.layout.PaddingValues) { // Placeholder for scrollable content androidx.compose.foundation.layout.Box(modifier = Modifier.padding(padding)) } ``` -------------------------------- ### Jetpack Compose SuggestionChip Example Source: https://developer.android.com/develop/ui/compose/components/chip A basic implementation of a suggestion chip. This composable is suitable for presenting dynamic hints or suggested actions, such as AI chat responses. It includes an `onClick` lambda for interactivity. ```kotlin import android.util.Log import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.SuggestionChip import androidx.compose.material3.Text import androidx.compose.runtime.Composable @OptIn(ExperimentalMaterial3Api::class) @Composable fun SuggestionChipExample() { SuggestionChip( onClick = { Log.d("Suggestion chip", "hello world") }, label = { Text("Suggestion chip") } ) } ``` -------------------------------- ### Customize a Rich Tooltip with Actions Source: https://developer.android.com/develop/ui/compose/components/tooltip This example demonstrates a rich tooltip with a title, a dismiss action button, and custom behavior for showing the tooltip. It utilizes TooltipState and coroutines for managing tooltip visibility. ```kotlin @Composable fun AdvancedRichTooltipExample( modifier: Modifier = Modifier, richTooltipSubheadText: String = "Custom Rich Tooltip", richTooltipText: String = "Rich tooltips support multiple lines of informational text.", richTooltipActionText: String = "Dismiss" ) { val tooltipState = rememberTooltipState() val coroutineScope = rememberCoroutineScope() TooltipBox( modifier = modifier, positionProvider = TooltipDefaults.rememberRichTooltipPositionProvider(), tooltip = { RichTooltip( title = { Text(richTooltipSubheadText) }, action = { Row { TextButton(onClick = { coroutineScope.launch { tooltipState.dismiss() } }) { Text(richTooltipActionText) } } }, ) { Text(richTooltipText) } }, state = tooltipState ) { IconButton(onClick = { coroutineScope.launch { tooltipState.show() } }) { Icon( imageVector = Icons.Filled.Camera, contentDescription = "Open camera" ) } } } Tooltips.kt ``` -------------------------------- ### Jetpack Compose InputChip Example Source: https://developer.android.com/develop/ui/compose/components/chip Demonstrates an input chip that is initially selected and can be dismissed by the user. Use this for elements like contacts in an email 'To:' field. The `onDismiss` lambda should handle necessary actions like network calls. ```kotlin import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Person import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.InputChip import androidx.compose.material3.InputChipDefaults import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier @OptIn(ExperimentalMaterial3Api::class) @Composable fun InputChipExample( text: String, onDismiss: () -> Unit, ) { var enabled by remember { mutableStateOf(true) } if (!enabled) return InputChip( onClick = { onDismiss() enabled = !enabled }, label = { Text(text) }, selected = enabled, avatar = { Icon( Icons.Filled.Person, contentDescription = "Localized description", Modifier.size(InputChipDefaults.AvatarSize) ) }, trailingIcon = { Icon( Icons.Default.Close, contentDescription = "Localized description", Modifier.size(InputChipDefaults.AvatarSize) ) }, ) } ``` -------------------------------- ### Vertical Divider Example Source: https://developer.android.com/develop/ui/compose/components/divider Demonstrates how to use VerticalDivider to separate items in a Row. Uses the color parameter to apply a custom color to the divider. ```kotlin import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material3.MaterialTheme import androidx.compose.material3.VerticalDivider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.foundation.layout.IntrinsicSize @Composable fun VerticalDividerExample() { Row( modifier = Modifier .fillMaxWidth() .height(IntrinsicSize.Min), horizontalArrangement = Arrangement.SpaceEvenly ) { Text("First item in row") VerticalDivider(color = MaterialTheme.colorScheme.secondary) Text("Second item in row") } } ``` -------------------------------- ### Implement a Basic Dial Time Picker Source: https://developer.android.com/develop/ui/compose/components/time-pickers Use `TimePicker` to display a dial for users to select a time. Initialize `TimePickerState` with the current time using `Calendar.getInstance()`. This example includes confirm and dismiss buttons. ```kotlin import androidx.compose.foundation.layout.Column import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.material3.TimePicker import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable import java.util.Calendar @Composable fun DialExample( onConfirm: () -> Unit, onDismiss: () -> Unit, ) { val currentTime = Calendar.getInstance() val timePickerState = rememberTimePickerState( initialHour = currentTime.get(Calendar.HOUR_OF_DAY), initialMinute = currentTime.get(Calendar.MINUTE), is24Hour = true, ) Column { TimePicker( state = timePickerState, ) Button(onClick = onDismiss) { Text("Dismiss picker") } Button(onClick = onConfirm) { Text("Confirm selection") } } } TimePickers.kt ``` -------------------------------- ### Basic BadgedBox Implementation Source: https://developer.android.com/develop/ui/compose/components/badges A basic example of `BadgedBox` displaying a default red circle badge over a mail icon. The `Badge` composable with no arguments renders the default badge. ```kotlin import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Mail import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.vector.ImageVector @Composable fun BadgeExample() { BadgedBox( badge = { Badge() // Default badge (small red circle) } ) { Icon( imageVector = Icons.Filled.Mail, contentDescription = "Email" ) } } ``` -------------------------------- ### Integrate selectable list into dynamic top app bar Source: https://developer.android.com/develop/ui/compose/components/app-bars-dynamic This example demonstrates integrating a selectable list with a dynamic top app bar. It uses a `Scaffold` to host the `AppBarSelectionActions` and a `LazyColumn` for the list items, allowing users to select items via long-press and see the top app bar update accordingly. ```kotlin import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.ListItem import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @OptIn(ExperimentalFoundationApi::class) @Composable private fun AppBarMultiSelectionExample( modifier: Modifier = Modifier, ) { val listItems by remember { mutableStateOf(listOf(1, 2, 3, 4, 5, 6)) } var selectedItems by rememberSaveable { mutableStateOf(setOf()) } Scaffold( modifier = modifier, topBar = { AppBarSelectionActions(selectedItems) } ) { innerPadding -> LazyColumn(contentPadding = innerPadding) { itemsIndexed(listItems) { _, index -> val isItemSelected = selectedItems.contains(index) ListItem( headlineContent = { Text("Item ${index + 1}") }, modifier = Modifier .combinedClickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = { /* click action */ }, onLongClick = { if (isItemSelected) selectedItems -= index else selectedItems += index } ) .padding(16.dp) ) } } } } AppBar.kt ``` -------------------------------- ### Advanced Dialog with Image and Buttons in Compose Source: https://developer.android.com/develop/ui/compose/components/dialog This advanced example demonstrates a custom dialog with an image, text, and action buttons. It's recommended to use AlertDialog for simpler two-button dialogs, but this approach is suitable for more complex dialogs with forms or multiple buttons. ```kotlin import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog @Composable fun DialogWithImage( onDismissRequest: () -> Unit, onConfirmation: () -> Unit, painter: Painter, imageDescription: String, ) { Dialog(onDismissRequest = { onDismissRequest() }) { // Draw a rectangle shape with rounded corners inside the dialog Card( modifier = Modifier .fillMaxWidth() .height(375.dp) .padding(16.dp), shape = RoundedCornerShape(16.dp), ) { Column( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Image( painter = painter, contentDescription = imageDescription, contentScale = ContentScale.Fit, modifier = Modifier .height(160.dp) ) Text( text = "This is a dialog with buttons and an image.", modifier = Modifier.padding(16.dp), ) Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.Center, ) { TextButton( onClick = { onDismissRequest() }, modifier = Modifier.padding(8.dp), ) { Text("Dismiss") } TextButton( onClick = { onConfirmation() }, modifier = Modifier.padding(8.dp), ) { Text("Confirm") } } } } } } ``` -------------------------------- ### Implement Tab-Based Navigation with PrimaryTabRow Source: https://developer.android.com/develop/ui/compose/components/tabs Use PrimaryTabRow and Tab composables to create a top navigation bar for switching between different app screens. This example manages navigation state using rememberNavController and rememberSaveable. ```kotlin @Composable fun NavigationTabExample(modifier: Modifier = Modifier) { val navController = rememberNavController() val startDestination = Destination.SONGS var selectedDestination by rememberSaveable { mutableIntStateOf(startDestination.ordinal) } Scaffold(modifier = modifier) { PrimaryTabRow(selectedTabIndex = selectedDestination, modifier = Modifier.padding(contentPadding)) { Destination.entries.forEachIndexed { index, destination -> Tab( selected = selectedDestination == index, onClick = { navController.navigate(route = destination.route) selectedDestination = index }, text = { Text( text = destination.label, maxLines = 2, overflow = TextOverflow.Ellipsis ) } ) } } AppNavHost(navController, startDestination) } } ``` -------------------------------- ### Implement an Assist Chip in Jetpack Compose Source: https://developer.android.com/develop/ui/compose/components/chip Use AssistChip to guide users during a task. It supports a leading icon for visual cues. Ensure necessary imports for Composable functions and Icons. ```kotlin import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.AssistChip import androidx.compose.material3.AssistChipDefaults import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import android.util.Log @Composable fun AssistChipExample() { AssistChip( onClick = { Log.d("Assist chip", "hello world") }, label = { Text("Assist chip") }, leadingIcon = { Icon( Icons.Filled.Settings, contentDescription = "Localized description", modifier = Modifier.size(AssistChipDefaults.IconSize) ) } ) } ``` -------------------------------- ### Manage AlertDialog State and Display Source: https://developer.android.com/develop/ui/compose/components/dialog This example shows how to manage the state of an `AlertDialog` using `remember { mutableStateOf(false) }`. The dialog is displayed when the state variable is true, and its `onDismissRequest` and `onConfirmation` lambdas update this state to close the dialog. ```kotlin @Composable fun DialogExamples() { // ... val openAlertDialog = remember { mutableStateOf(false) } // ... when { // ... openAlertDialog.value -> { AlertDialogExample( onDismissRequest = { openAlertDialog.value = false }, onConfirmation = { openAlertDialog.value = false println("Confirmation registered") // Add logic here to handle confirmation. }, dialogTitle = "Alert dialog example", dialogText = "This is an example of an alert dialog with buttons.", icon = Icons.Default.Info ) } } } } Dialog.kt ``` -------------------------------- ### Switch with Custom Thumb Icon Source: https://developer.android.com/develop/ui/compose/components/switch Customize the thumb of the Switch using the `thumbContent` parameter. This example shows how to display a checkmark icon when the switch is checked. Ensure necessary imports for `Icon` and `Icons.Filled.Check` are present. ```kotlin import androidx.compose.material3.Switch import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.material3.Icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.material3.SwitchDefaults @Composable fun SwitchWithIconExample() { var checked by remember { mutableStateOf(true) } Switch( checked = checked, onCheckedChange = { checked = it }, thumbContent = if (checked) { { Icon( imageVector = Icons.Filled.Check, contentDescription = null, modifier = Modifier.size(SwitchDefaults.IconSize), ) } } else { null } ) } ``` -------------------------------- ### Center Aligned Top App Bar Example Source: https://developer.android.com/develop/ui/compose/components/app-bars Use `CenterAlignedTopAppBar` for a centered title. This example integrates with `pinnedScrollBehavior` to collapse the bar on scroll. ```kotlin import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.ui.input.nestedscroll.nestedScroll @OptIn(ExperimentalMaterial3Api::class) @Composable fun CenterAlignedTopAppBarExample() { val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState()) Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { CenterAlignedTopAppBar( colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text( "Centered Top App Bar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* do something */ }) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Localized description" ) } }, actions = { IconButton(onClick = { /* do something */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, scrollBehavior = scrollBehavior, ) }, ) { ScrollContent(it) } } @Composable fun ScrollContent(padding: androidx.compose.foundation.layout.PaddingValues) { // Placeholder for scrollable content androidx.compose.foundation.layout.Box(modifier = Modifier.padding(padding)) } ``` -------------------------------- ### Basic Search Bar with Suggestions Source: https://developer.android.com/develop/ui/compose/components/search-bar This snippet demonstrates a basic implementation of the SearchBar composable, including handling user input, search queries, and displaying a list of suggestions. Use this when you need a persistent search field with dynamic suggestion results. ```kotlin @OptIn(ExperimentalMaterial3Api::class) @Composable fun SimpleSearchBar( textFieldState: TextFieldState, onSearch: (String) -> Unit, searchResults: List, modifier: Modifier = Modifier ) { // Controls expansion state of the search bar var expanded by rememberSaveable { mutableStateOf(false) } Box( modifier .fillMaxSize() .semantics { isTraversalGroup = true } ) { SearchBar( modifier = Modifier .align(Alignment.TopCenter) .semantics { traversalIndex = 0f }, inputField = { SearchBarDefaults.InputField( query = textFieldState.text.toString(), onQueryChange = { textFieldState.edit { replace(0, length, it) } }, onSearch = { onSearch(textFieldState.text.toString()) expanded = false }, expanded = expanded, onExpandedChange = { expanded = it }, placeholder = { Text("Search") } ) }, expanded = expanded, onExpandedChange = { expanded = it }, ) { // Display search results in a scrollable column Column(Modifier.verticalScroll(rememberScrollState())) { searchResults.forEach { result -> ListItem( headlineContent = { Text(result) }, modifier = Modifier .clickable { textFieldState.edit { replace(0, length, result) } expanded = false } .fillMaxWidth() ) } } } } } SearchBar.kt ``` -------------------------------- ### Filled Card with Custom Colors Source: https://developer.android.com/develop/ui/compose/components/card Implement a filled card using the `colors` parameter to set the container color. This example uses `MaterialTheme.colorScheme.surfaceVariant`. ```kotlin import androidx.compose.foundation.layout.size import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun FilledCardExample() { Card( colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceVariant, ), modifier = Modifier .size(width = 240.dp, height = 100.dp) ) { Text( text = "Filled", modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) } } ``` -------------------------------- ### Elevated Card with Custom Elevation Source: https://developer.android.com/develop/ui/compose/components/card Implement an elevated card using the `ElevatedCard` composable and control its shadow with the `elevation` property. This example sets a `defaultElevation` of 6.dp. ```kotlin import androidx.compose.foundation.layout.size import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun ElevatedCardExample() { ElevatedCard( elevation = CardDefaults.cardElevation( defaultElevation = 6.dp ), modifier = Modifier .size(width = 240.dp, height = 100.dp) ) { Text( text = "Elevated", modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) } } ``` -------------------------------- ### Small Floating Action Button with Custom Colors - Compose Source: https://developer.android.com/develop/ui/compose/components/fab Implement a smaller FAB using `SmallFloatingActionButton`. This example demonstrates how to apply custom `containerColor` and `contentColor`. ```kotlin @Composable fun SmallExample(onClick: () -> Unit) { SmallFloatingActionButton( onClick = { onClick() }, containerColor = MaterialTheme.colorScheme.secondaryContainer, contentColor = MaterialTheme.colorScheme.secondary ) { Icon(Icons.Filled.Add, "Small floating action button.") } } FloatingActionButton.kt ``` -------------------------------- ### Large Floating Action Button with Circle Shape - Compose Source: https://developer.android.com/develop/ui/compose/components/fab Create a larger FAB with `LargeFloatingActionButton`. This example uses `CircleShape` for a round button, but other `Shape` instances can be used. ```kotlin @Composable fun LargeExample(onClick: () -> Unit) { LargeFloatingActionButton( onClick = { onClick() }, shape = CircleShape, ) { Icon(Icons.Filled.Add, "Large floating action button") } } FloatingActionButton.kt ``` -------------------------------- ### Integrate Navigation with NavController Source: https://developer.android.com/develop/ui/compose/components/app-bars-navigate This snippet shows how to integrate the `TopBarNavigationExample` composable with Jetpack Navigation. It demonstrates passing a lambda to `TopBarNavigationExample` that calls `navController.popBackStack()` to handle the back navigation. This is typically done when building your navigation graph. ```kotlin import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController @Composable fun AppNavigation() { val navController = rememberNavController() NavHost(navController, startDestination = "home") { composable("topBarNavigationExample") { TopBarNavigationExample { navController.popBackStack() } } // Other destinations... } } ``` -------------------------------- ### Create a Basic Dropdown Menu in Compose Source: https://developer.android.com/develop/ui/compose/components/menu Implement a minimal DropdownMenu with two selectable options. The 'expanded' state controls visibility, and 'onDismissRequest' handles closing. An IconButton serves as the trigger. ```kotlin import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun MinimalDropdownMenu() { var expanded by remember { mutableStateOf(false) } Box( modifier = Modifier .padding(16.dp) ) { IconButton(onClick = { expanded = !expanded }) { Icon(Icons.Default.MoreVert, contentDescription = "More options") } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { DropdownMenuItem( text = { Text("Option 1") }, onClick = { /* Do something... */ } ) DropdownMenuItem( text = { Text("Option 2") }, onClick = { /* Do something... */ } ) } } } ``` -------------------------------- ### Create a scrollable DropdownMenu Source: https://developer.android.com/develop/ui/compose/components/menu This code creates a scrollable DropdownMenu with 100 placeholder items. All items are created in the composition, not lazily. ```kotlin val expanded = remember { mutableStateOf(false) } IconButton(onClick = { expanded.value = !expanded.value }) { Icon(Icons.Filled.MoreVert, contentDescription = "More") } DropdownMenu( expanded = expanded.value, onDismissRequest = { expanded.value = false }) { repeat(100) { DropdownMenuItem(text = { Text("Item $it") }, onClick = { /* Do something */ }) } } ``` -------------------------------- ### Large Top App Bar with Scroll Behavior Source: https://developer.android.com/develop/ui/compose/components/app-bars Use `LargeTopAppBar` for an app bar that occupies more space and has greater padding. This example demonstrates `exitUntilCollapsedScrollBehavior()` which collapses the bar on scroll and expands it when scrolling to the end. ```kotlin @Composable fun LargeTopAppBarExample() { val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState()) Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { LargeTopAppBar( colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text( "Large Top App Bar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /* do something */ }) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Localized description" ) } }, actions = { IconButton(onClick = { /* do something */ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, scrollBehavior = scrollBehavior ) }, ) { ScrollContent(it) } } ``` -------------------------------- ### Basic Snackbar Implementation in Compose Source: https://developer.android.com/develop/ui/compose/components/snackbar Implement a basic snackbar using `SnackbarHost` and `SnackbarHostState`. Requires a `CoroutineScope` to call `showSnackbar()`. This is typically used within a `Scaffold` to display feedback on UI events. ```kotlin val scope = rememberCoroutineScope() val snackbarHostState = remember { SnackbarHostState() } Scaffold( snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, floatingActionButton = { ExtendedFloatingActionButton( text = { Text("Show snackbar") }, icon = { Icon(Icons.Filled.Image, contentDescription = "") }, onClick = { scope.launch { snackbarHostState.showSnackbar("Snackbar") } } ) } ) { // Screen content } ``` -------------------------------- ### Implement a Modal Date Range Picker Source: https://developer.android.com/develop/ui/compose/components/datepickers Use this composable to allow users to select a range of dates in a modal dialog. It provides the selected start and end dates in milliseconds via the `onDateRangeSelected` callback. ```kotlin @Composable fun DateRangePickerModal( onDateRangeSelected: (Pair) -> Unit, onDismiss: () -> Unit ) { val dateRangePickerState = rememberDateRangePickerState() DatePickerDialog( onDismissRequest = onDismiss, confirmButton = { TextButton( onClick = { onDateRangeSelected( Pair( dateRangePickerState.selectedStartDateMillis, dateRangePickerState.selectedEndDateMillis ) ) onDismiss() } ) { Text("OK") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } } ) { DateRangePicker( state = dateRangePickerState, title = { Text( text = "Select date range" ) }, showModeToggle = false, modifier = Modifier .fillMaxWidth() .height(500.dp) .padding(16.dp) ) } } DatePickers.kt ``` -------------------------------- ### Implement a Modal Date Picker with Input Mode Source: https://developer.android.com/develop/ui/compose/components/datepickers This composable displays a modal date picker that allows users to input the date directly. It uses `DisplayMode.Input` for the initial display mode. ```kotlin @Composable fun DatePickerModalInput( onDateSelected: (Long?) -> Unit, onDismiss: () -> Unit ) { val datePickerState = rememberDatePickerState(initialDisplayMode = DisplayMode.Input) DatePickerDialog( onDismissRequest = onDismiss, confirmButton = { TextButton(onClick = { onDateSelected(datePickerState.selectedDateMillis) onDismiss() }) { Text("OK") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } } ) { DatePicker(state = datePickerState) } } DatePickers.kt ``` -------------------------------- ### Use TimePicker State in Compose Source: https://developer.android.com/develop/ui/compose/components/time-pickers Demonstrates how to initialize and use `TimePickerState` to capture user selections. Pass the state to `onConfirm` to access the selected hour and minute. ```kotlin import androidx.compose.foundation.layout.Column import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.material3.TimePicker import androidx.compose.material3.TimePickerState import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.* import androidx.compose.ui.tooling.preview.Preview import java.util.Calendar @Composable fun DialUseStateExample( onConfirm: (TimePickerState) -> Unit, onDismiss: () -> Unit, ) { val currentTime = Calendar.getInstance() val timePickerState = rememberTimePickerState( initialHour = currentTime.get(Calendar.HOUR_OF_DAY), initialMinute = currentTime.get(Calendar.MINUTE), is24Hour = true, ) Column { TimePicker( state = timePickerState, ) Button(onClick = onDismiss) { Text("Dismiss picker") } Button(onClick = { onConfirm(timePickerState) }) { Text("Confirm selection") } } } @Preview @Composable fun DialUseStateExamplePreview() { // Preview requires a placeholder for onConfirm and onDismiss DialUseStateExample( onConfirm = { /* Do nothing for preview */ }, onDismiss = { /* Do nothing for preview */ } ) } ``` ```kotlin import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.tooling.preview.Preview import java.util.Calendar import java.text.SimpleDateFormat import java.util.Locale // Assume formatter and showDialExample are defined elsewhere // For preview purposes, let's define them here: private val formatter = SimpleDateFormat("HH:mm", Locale.getDefault()) private var showDialExample by mutableStateOf(true) @Composable fun TimePickerUsageExample() { var selectedTime: TimePickerState? by remember { mutableStateOf(null) } if (showDialExample) { DialUseStateExample( onDismiss = { showDialExample = false }, onConfirm = { time -> selectedTime = time showDialExample = false }, ) } else { if (selectedTime != null) { val cal = Calendar.getInstance() cal.set(Calendar.HOUR_OF_DAY, selectedTime!!.hour) cal.set(Calendar.MINUTE, selectedTime!!.minute) cal.isLenient = false Text("Selected time = ${formatter.format(cal.time)}") } else { Text("No time selected.") } } } @Preview @Composable fun TimePickerUsageExamplePreview() { TimePickerUsageExample() } ``` -------------------------------- ### Basic Slider Implementation Source: https://developer.android.com/develop/ui/compose/components/slider A simple continuous slider allowing selection from 0.0 to 1.0. It displays the current selected value. ```kotlin import androidx.compose.foundation.layout.Column import androidx.compose.material3.Slider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.tooling.preview.Preview @Preview @Composable fun SliderMinimalExample() { var sliderPosition by remember { mutableFloatStateOf(0f) } Column { Slider( value = sliderPosition, onValueChange = { sliderPosition = it } ) Text(text = sliderPosition.toString()) } } ``` -------------------------------- ### Create a Fully Customized Pull-to-Refresh Indicator Source: https://developer.android.com/develop/ui/compose/components/pull-to-refresh Implement a custom indicator composable that leverages animations for transitions between states. This example shows how to use `Crossfade` to switch between a cloud icon and a progress indicator based on the refresh state and pull distance. ```kotlin @Composable fun PullToRefreshCustomIndicatorSample( items: List, isRefreshing: Boolean, onRefresh: () -> Unit, modifier: Modifier = Modifier ) { val state = rememberPullToRefreshState() PullToRefreshBox( isRefreshing = isRefreshing, onRefresh = onRefresh, modifier = modifier, state = state, indicator = { MyCustomIndicator( state = state, isRefreshing = isRefreshing, modifier = Modifier.align(Alignment.TopCenter) ) } ) { LazyColumn(Modifier.fillMaxSize()) { items(items) { ListItem({ Text(text = it) }) } } } } // ... @Composable fun MyCustomIndicator( state: PullToRefreshState, isRefreshing: Boolean, modifier: Modifier = Modifier, ) { Box( modifier = modifier.pullToRefresh( state = state, isRefreshing = isRefreshing, threshold = PositionalThreshold, onRefresh = { } ), contentAlignment = Alignment.Center ) { Crossfade( targetState = isRefreshing, animationSpec = tween(durationMillis = CROSSFADE_DURATION_MILLIS), modifier = Modifier.align(Alignment.Center) ) { refreshing -> if (refreshing) { CircularProgressIndicator(Modifier.size(SPINNER_SIZE)) } else { val distanceFraction = { state.distanceFraction.coerceIn(0f, 1f) } Icon( imageVector = Icons.Filled.CloudDownload, contentDescription = "Refresh", modifier = Modifier .size(18.dp) .graphicsLayer { val progress = distanceFraction() this.alpha = progress this.scaleX = progress this.scaleY = progress } ) } } } } PullToRefreshBox.kt ``` -------------------------------- ### Implement Top App Bar with Navigation Icon Source: https://developer.android.com/develop/ui/compose/components/app-bars-navigate This composable defines a top app bar with a navigation icon. It accepts a navigateBack lambda to handle the navigation action when the icon is clicked. Use this when you need a functional navigation icon in your app bar. ```kotlin import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview @OptIn(ExperimentalMaterial3Api::class) @Composable fun TopBarNavigationExample( navigateBack: () -> Unit, ) { Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text( "Navigation example", ) }, navigationIcon = { IconButton(onClick = navigateBack) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Localized description" ) } }, ) }, ) { Text( "Click the back button to pop from the back stack.", modifier = Modifier.padding(it), ) } } @Preview @Composable fun PreviewTopBarNavigationExample() { TopBarNavigationExample { /* No-op for preview */ } } ```