### Simple TextField Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/TextField/examples.md A basic example of a TextField with a label. This serves as a starting point for more complex configurations. ```kotlin @Preview @Composable fun SimpleTextFieldSample() { TextField( state = rememberTextFieldState(), lineLimits = TextFieldLineLimits.SingleLine, label = { Text("Label") }, ) } ``` -------------------------------- ### DropdownMenuItem Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/DropdownMenuItem Demonstrates how to create and configure DropdownMenuItem composables within a DropdownMenu. Includes examples with text, icons, and a trailing element. Ensure proper accessibility by using TooltipBox for icons. ```kotlin import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Email import androidx.compose.material.icons.outlined.Edit import androidx.compose.material.icons.outlined.Settings import androidx.compose.material.icons.Icons.Default import androidx.compose.material.icons.Icons.Outlined import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.PlainTooltip import androidx.compose.material3.Text import androidx.compose.material3.TooltipBox import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.TooltipState import androidx.compose.material3.rememberTooltipState import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi 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.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.paneTitle import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview @OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class) @Preview @Composable fun MenuSample() { var expanded by remember { mutableStateOf(false) } Box(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.TopStart)) { // Icon button should have a tooltip associated with it for a11y. TooltipBox( positionProvider = TooltipDefaults.rememberTooltipPositionProvider(TooltipAnchorPosition.Above), tooltip = { PlainTooltip( Modifier.semantics { // TODO(b/496338253): Remove this modifier once bug where tooltip text is // not announced by a11y screen readers is resolved. liveRegion = LiveRegionMode.Assertive paneTitle = "Localized description" } ) { Text("Localized description") } }, state = rememberTooltipState(), ) { IconButton(onClick = { expanded = true }) { Icon(Icons.Default.MoreVert, contentDescription = "Localized description") } } DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { DropdownMenuItem( text = { Text("Edit") }, onClick = { /* Handle edit! */ }, leadingIcon = { Icon(Icons.Outlined.Edit, contentDescription = null) }, ) DropdownMenuItem( text = { Text("Settings") }, onClick = { /* Handle settings! */ }, leadingIcon = { Icon(Icons.Outlined.Settings, contentDescription = null) }, ) HorizontalDivider() DropdownMenuItem( text = { Text("Send Feedback") }, onClick = { /* Handle send feedback! */ }, leadingIcon = { Icon(Icons.Outlined.Email, contentDescription = null) }, trailingIcon = { Text("F11", textAlign = TextAlign.Center) }, ) } } } ``` -------------------------------- ### Basic Switch Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/Switch/api.md Demonstrates how to use the Switch component with basic state management. ```kotlin ```kotlin @Preview @Composable fun SwitchSample() { var checked by remember { mutableStateOf(true) } Switch( modifier = Modifier.semantics { contentDescription = "Demo" }, checked = checked, onCheckedChange = { checked = it }) } ``` ``` -------------------------------- ### Basic Surface Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/Surface/examples.md A simple Surface composable displaying text. This is the most basic usage. ```kotlin import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview @Preview @Composable fun SurfaceSample() { Surface { Text("Text on Surface") } } ``` -------------------------------- ### SecondaryTextTabs Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/SecondaryTabRow Demonstrates how to implement SecondaryTabRow with text-based tabs. This example shows state management for the selected tab and how to display different content based on the selection. ```kotlin ```kotlin @Preview @Composable @OptIn(ExperimentalMaterial3Api::class) fun SecondaryTextTabs() { var state by remember { mutableStateOf(0) } val titles = listOf("Tab 1", "Tab 2", "Tab 3 with lots of text") Column { SecondaryTabRow(selectedTabIndex = state) { titles.forEachIndexed { index, title -> Tab( selected = state == index, onClick = { state = index }, text = { Text(text = title, maxLines = 2, overflow = TextOverflow.Ellipsis) }, ) } } Text( modifier = Modifier.align(Alignment.CenterHorizontally), text = "Secondary tab ${state + 1} selected", style = MaterialTheme.typography.bodyLarge, ) } } ``` ``` -------------------------------- ### SecondaryTextTabs Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/SecondaryTabRow/examples.md Demonstrates how to implement SecondaryTabRow with text-based tabs. This example shows state management for the selected tab and how to display different content based on the selection. ```kotlin @Preview @Composable @OptIn(ExperimentalMaterial3Api::class) fun SecondaryTextTabs() { var state by remember { mutableStateOf(0) } val titles = listOf("Tab 1", "Tab 2", "Tab 3 with lots of text") Column { SecondaryTabRow(selectedTabIndex = state) { titles.forEachIndexed { index, title -> Tab( selected = state == index, onClick = { state = index }, text = { Text(text = title, maxLines = 2, overflow = TextOverflow.Ellipsis) }, ) } } Text( modifier = Modifier.align(Alignment.CenterHorizontally), text = "Secondary tab ${state + 1} selected", style = MaterialTheme.typography.bodyLarge, ) } } ``` -------------------------------- ### EnterAlwaysTopAppBar Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/TopAppBar Demonstrates a TopAppBar that collapses when scrolling up and reappears when scrolling down. Requires `ExperimentalMaterial3Api` and `ExperimentalMaterial3ExpressiveApi`. ```kotlin /** * A sample for a small [TopAppBar] that collapses when the content is scrolled up, and appears when * the content scrolled down. */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class) @Preview @Composable fun EnterAlwaysTopAppBar() { val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { TopAppBar( title = { Text("TopAppBar", maxLines = 1, overflow = TextOverflow.Ellipsis) }, subtitle = { Text("Subtitle", maxLines = 1, overflow = TextOverflow.Ellipsis) }, navigationIcon = { TooltipBox( positionProvider = TooltipDefaults.rememberTooltipPositionProvider( TooltipAnchorPosition.Above ), tooltip = { PlainTooltip( modifier = Modifier.semantics { // TODO(b/496338253): Remove this modifier once bug where // tooltip text is not announced by a11y screen readers // is resolved. liveRegion = LiveRegionMode.Assertive paneTitle = "Menu" } ) { Text("Menu") } }, state = rememberTooltipState(), ) { IconButton(onClick = { /* doSomething() */ }) { Icon(imageVector = Icons.Filled.Menu, contentDescription = "Menu") } } }, actions = { TooltipBox( positionProvider = TooltipDefaults.rememberTooltipPositionProvider( TooltipAnchorPosition.Above ), tooltip = { PlainTooltip( modifier = Modifier.semantics { // TODO(b/496338253): Remove this modifier once bug where // tooltip text is not announced by a11y screen readers // is resolved. liveRegion = LiveRegionMode.Assertive paneTitle = "Add to favorites" } ) { Text("Add to favorites") } }, state = rememberTooltipState(), ) { IconButton(onClick = { /* doSomething() */ }) { Icon( imageVector = Icons.Filled.Favorite, contentDescription = "Add to favorites", ) } } }, scrollBehavior = scrollBehavior, ) }, content = { innerPadding -> LazyColumn( modifier = Modifier.padding(innerPadding), verticalArrangement = Arrangement.spacedBy(8.dp), ) { val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), ) } } }, ) } ``` -------------------------------- ### Clickable Surface Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/Surface Demonstrates a Surface that increments a counter when clicked. Requires state management. ```kotlin import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview @Preview @Composable fun ClickableSurfaceSample() { var count by remember { mutableStateOf(0) } Surface(onClick = { count++ }) { Text("Clickable Surface. Count: $count") } } ``` -------------------------------- ### Get Selected Start Date from DateRangePickerState Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/functions/getSelectedStartDate/api.md Use this function to retrieve the selected start date from a DateRangePickerState. It returns a LocalDate object or null if no date has been selected. ```kotlin import java.time.LocalDate import androidx.compose.material3.DateRangePickerState import androidx.annotation.RequiresApi @RequiresApi(26) fun DateRangePickerState.getSelectedStartDate(): LocalDate? ``` -------------------------------- ### SimpleTopAppBarWithAdaptiveActions Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/AppBarRow/api.md Demonstrates a basic implementation of a TopAppBar with adaptive actions. This snippet shows how to set up the app bar and its content. ```kotlin verticalArrangement = Arrangement.spacedBy(8.dp), ) { val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), ) } } }, ) } ``` ``` -------------------------------- ### Simple SearchBar Sample Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/SearchBar Demonstrates a basic implementation of the SearchBar with an input field and expandable search results. ```kotlin @Preview @Composable fun SimpleSearchBarSample() { val searchBarState = rememberSearchBarState() val textFieldState = rememberTextFieldState() val scope = rememberCoroutineScope() val inputField = @Composable { SearchBarDefaults.InputField( textFieldState = textFieldState, searchBarState = searchBarState, onSearch = { scope.launch { searchBarState.animateToCollapsed() } }, placeholder = { Text(modifier = Modifier.clearAndSetSemantics {}, text = "Search") }, leadingIcon = { SampleLeadingIcon(searchBarState, scope) }, trailingIcon = { SampleTrailingIcon() }, ) } SearchBar(state = searchBarState, inputField = inputField) ExpandedFullScreenSearchBar(state = searchBarState, inputField = inputField) { SampleSearchResults( onResultClick = { result -> textFieldState.setTextAndPlaceCursorAtEnd(result) scope.launch { searchBarState.animateToCollapsed() } } ) } } ``` -------------------------------- ### Default OutlinedTextField Padding Values Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/objects/TextFieldDefaults Use this function to get the default padding values for an outlined text field. You can override individual padding values like start, top, end, and bottom. ```kotlin fun outlinedTextFieldPadding( start: Dp = TextFieldPadding, top: Dp = TextFieldPadding, end: Dp = TextFieldPadding, bottom: Dp = TextFieldPadding, ): PaddingValues ``` -------------------------------- ### Simple SearchBar Sample Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/SearchBar/examples.md Demonstrates a basic implementation of the SearchBar with an input field and an expanded full-screen view for search results. Use this for standard search functionality. ```kotlin import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Search import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.SearchBar import androidx.compose.material3.SearchBarDefaults import androidx.compose.material3.Text import androidx.compose.material3.TextFieldState import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.rememberSearchBarState import androidx.compose.material3.rememberTextFieldState import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Preview @Composable fun SimpleSearchBarSample() { val searchBarState = rememberSearchBarState() val textFieldState = rememberTextFieldState() val scope = rememberCoroutineScope() val inputField = @Composable { SearchBarDefaults.InputField( textFieldState = textFieldState, searchBarState = searchBarState, onSearch = { scope.launch { searchBarState.animateToCollapsed() } }, placeholder = { Text(modifier = Modifier.clearAndSetSemantics {}, text = "Search") }, leadingIcon = { SampleLeadingIcon(searchBarState, scope) }, trailingIcon = { SampleTrailingIcon() }, ) } SearchBar( state = searchBarState, inputField = inputField ) ExpandedFullScreenSearchBar( state = searchBarState, inputField = inputField ) { SampleSearchResults( onResultClick = { textFieldState.setTextAndPlaceCursorAtEnd(it) scope.launch { searchBarState.animateToCollapsed() } } ) } } @Composable private fun SampleLeadingIcon( searchBarState: SearchBarState, scope: CoroutineScope ) { if (searchBarState.isJustLandscaped) { IconButton( onClick = { scope.launch { searchBarState.animateToCollapsed() } } ) { Icon(Icons.Default.ArrowBack, contentDescription = "Back") } } else { Icon( Icons.Default.Search, contentDescription = null, modifier = Modifier.padding(start = 16.dp) ) } } @Composable private fun SampleTrailingIcon() { val textFieldState = rememberTextFieldState() SearchBarDefaults.TrailingIcon( onClick = { textFieldState.setTextAndPlaceCursorAtEnd("") }, icon = { Icon( Icons.Default.MoreVert, contentDescription = null, ) } ) } @Composable private fun SampleSearchResults( modifier: Modifier = Modifier, onResultClick: (String) -> Unit ) { val results = listOf("Item 1", "Item 2", "Item 3") LazyColumn(modifier = modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp)) { items(results) { Text( text = it, modifier = Modifier .fillMaxWidth() .clickable { onResultClick(it) } .padding(vertical = 14.dp) ) } } } ``` -------------------------------- ### Get Content Padding for Button Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/objects/ButtonDefaults/api.md Calculates recommended PaddingValues for button content, considering button height, and the presence of start or end icons. The padding is based on predefined container heights and may not interpolate directly from the provided buttonHeight. ```kotlin @ExperimentalMaterial3ExpressiveApi fun contentPaddingFor( buttonHeight: Dp, hasStartIcon: Boolean = false, hasEndIcon: Boolean = false, ): PaddingValues ``` -------------------------------- ### Get Content Padding for Button with Icon Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/objects/ButtonDefaults Calculates recommended PaddingValues for button content, considering button height and the presence of start or end icons. The padding is based on predefined size constants and may not interpolate directly with the provided buttonHeight. ```kotlin @OptIn(ExperimentalMaterial3ExpressiveApi::class) fun contentPaddingFor( buttonHeight: Dp, hasStartIcon: Boolean = false, hasEndIcon: Boolean = false, ): PaddingValues ``` -------------------------------- ### Basic Assist Chip Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/AssistChip Demonstrates the basic usage of an Assist Chip with a label and a leading icon. This is useful for providing suggested actions or information. ```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 @Preview @Composable fun AssistChipSample() { AssistChip( onClick = { /* Do something! */ }, label = { Text("Assist Chip") }, leadingIcon = { Icon( Icons.Filled.Settings, contentDescription = "Localized description", Modifier.size(AssistChipDefaults.IconSize), ) }, ) } ``` -------------------------------- ### Basic DropdownMenu Sample Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/DropdownMenu Demonstrates a basic DropdownMenu with several menu items, including icons and a trailing text. ```kotlin @OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class) @Preview @Composable fun MenuSample() { var expanded by remember { mutableStateOf(false) } Box(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.TopStart)) { // Icon button should have a tooltip associated with it for a11y. TooltipBox( positionProvider = TooltipDefaults.rememberTooltipPositionProvider(TooltipAnchorPosition.Above), tooltip = { PlainTooltip( Modifier.semantics { // TODO(b/496338253): Remove this modifier once bug where tooltip text is // not announced by a11y screen readers is resolved. liveRegion = LiveRegionMode.Assertive paneTitle = "Localized description" } ) { Text("Localized description") } }, state = rememberTooltipState(), ) { IconButton(onClick = { expanded = true }) { Icon(Icons.Default.MoreVert, contentDescription = "Localized description") } } DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { DropdownMenuItem( text = { Text("Edit") }, onClick = { /* Handle edit! */ }, leadingIcon = { Icon(Icons.Outlined.Edit, contentDescription = null) }, ) DropdownMenuItem( text = { Text("Settings") }, onClick = { /* Handle settings! */ }, leadingIcon = { Icon(Icons.Outlined.Settings, contentDescription = null) }, ) HorizontalDivider() DropdownMenuItem( text = { Text("Send Feedback") }, onClick = { /* Handle send feedback! */ }, leadingIcon = { Icon(Icons.Outlined.Email, contentDescription = null) }, trailingIcon = { Text("F11", textAlign = TextAlign.Center) }, ) } } } ``` -------------------------------- ### Slider with Custom Track Icons Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/Slider/examples.md This example shows how to customize the Slider's track to display icons at the start and end. It uses `SliderDefaults.Track` and custom drawing logic to position and render the icons based on the slider's value and state. Ensure `ExperimentalMaterial3ExpressiveApi` is opt-in. ```kotlin import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MusicOff import androidx.compose.material.icons.filled.MusicNote import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Slider import androidx.compose.material3.SliderDefaults import androidx.compose.material3.Text import androidx.compose.material3.rememberSliderState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.drawWithContent import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Preview @Composable fun SliderWithTrackIconsSample() { val sliderState = rememberSliderState( valueRange = 0f..100f, onValueChangeFinished = { // launch some business logic update with the state you hold // viewModel.updateSelectedSliderValue(sliderPosition) }, ) val interactionSource = remember { MutableInteractionSource() } val startIcon = rememberVectorPainter(Icons.Filled.MusicNote) val endIcon = rememberVectorPainter(Icons.Filled.MusicOff) Column(modifier = Modifier.padding(horizontal = 16.dp)) { Text(text = "%.2f".format(sliderState.value)) Slider( state = sliderState, interactionSource = interactionSource, track = { val iconSize = DpSize(20.dp, 20.dp) val iconPadding = 10.dp val thumbTrackGapSize = 6.dp val activeIconColor = SliderDefaults.colors().activeTickColor val inactiveIconColor = SliderDefaults.colors().inactiveTickColor val trackIconStart: DrawScope.(Offset, Color) -> Unit = { offset, color -> translate(offset.x + iconPadding.toPx(), offset.y) { with(startIcon) { draw(iconSize.toSize(), colorFilter = ColorFilter.tint(color)) } } } val trackIconEnd: DrawScope.(Offset, Color) -> Unit = { offset, color -> translate(offset.x - iconPadding.toPx() - iconSize.toSize().width, offset.y) { with(endIcon) { draw(iconSize.toSize(), colorFilter = ColorFilter.tint(color)) } } } SliderDefaults.Track( sliderState = sliderState, modifier = Modifier.height(36.dp).drawWithContent { drawContent() val yOffset = size.height / 2 - iconSize.toSize().height / 2 val activeTrackStart = 0f val activeTrackEnd = size.width * sliderState.coercedValueAsFraction - thumbTrackGapSize.toPx() val inactiveTrackStart = activeTrackEnd + thumbTrackGapSize.toPx() * 2 val inactiveTrackEnd = size.width val activeTrackWidth = activeTrackEnd - activeTrackStart val inactiveTrackWidth = inactiveTrackEnd - inactiveTrackStart if ( iconSize.toSize().width < activeTrackWidth - iconPadding.toPx() * 2 ) { trackIconStart(Offset(activeTrackStart, yOffset), activeIconColor) trackIconEnd(Offset(activeTrackEnd, yOffset), activeIconColor) } if ( iconSize.toSize().width < inactiveTrackWidth - iconPadding.toPx() * 2 ) { trackIconStart( Offset(inactiveTrackStart, yOffset), inactiveIconColor, ) trackIconEnd(Offset(inactiveTrackEnd, yOffset), inactiveIconColor) } }, trackCornerSize = 12.dp, drawStopIndicator = null, thumbTrackGapSize = thumbTrackGapSize, ) }, ) } } ``` -------------------------------- ### MaterialTheme Sample with Dynamic Colors and Custom Styles Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/MaterialTheme/api.md Demonstrates setting up a MaterialTheme with dynamic color support, custom light/dark color schemes, typography, and shapes. This setup is useful for defining the overall look and feel of your application. ```kotlin import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material3.ColorScheme import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Shapes import androidx.compose.material3.Text import androidx.compose.material3.Typography import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.dp import androidx.compose.ui.tooling.preview.Preview @Preview @Composable fun MaterialThemeSample() { val isDarkTheme = isSystemInDarkTheme() val supportsDynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S val lightColorScheme = lightColorScheme(primary = Color(0xFF1EB980)) val darkColorScheme = darkColorScheme(primary = Color(0xFF66ffc7)) val colorScheme = when { supportsDynamicColor && isDarkTheme -> { dynamicDarkColorScheme(LocalContext.current) } supportsDynamicColor && !isDarkTheme -> { dynamicLightColorScheme(LocalContext.current) } isDarkTheme -> darkColorScheme else -> lightColorScheme } val typography = Typography( displaySmall = TextStyle(fontWeight = FontWeight.W100, fontSize = 96.sp), labelLarge = TextStyle(fontWeight = FontWeight.W600, fontSize = 14.sp), ) val shapes = Shapes(extraSmall = RoundedCornerShape(3.0.dp), small = RoundedCornerShape(6.0.dp)) MaterialTheme(colorScheme = colorScheme, typography = typography, shapes = shapes) { val currentTheme = if (!isSystemInDarkTheme()) "light" else "dark" ExtendedFloatingActionButton( text = { Text("FAB with text style and color from $currentTheme theme") }, icon = { Icon(Icons.Filled.Favorite, contentDescription = "Localized Description") }, onClick = {}, ) } } ``` -------------------------------- ### Start Position for FAB Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/classes/FloatingToolbarHorizontalFabPosition/api.md Represents the start position for a FloatingActionButton within a HorizontalFloatingToolbar. Use this when you want the FAB aligned to the start. ```kotlin val Start = FloatingToolbarHorizontalFabPosition(0) ``` -------------------------------- ### Simple TopAppBar with Adaptive Actions Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/AppBarRow/examples.md Demonstrates a basic TopAppBar implementation that can adapt its actions based on screen size. This example shows how to integrate it within a scrollable list. ```kotlin val list = (0..75).map { it.toString() } items(count = list.size) { Text( text = list[it], style = MaterialTheme.typography.bodyLarge, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), ) } ``` -------------------------------- ### Selected Start Date Property Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/interfaces/DateRangePickerState Represents the selected start date as a UTC milliseconds timestamp. Null indicates no start date is selected. ```kotlin val selectedStartDateMillis: Long? ``` -------------------------------- ### TooltipAnchorPosition Start Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/classes/TooltipAnchorPosition/api.md Places the tooltip at the start of the anchor. ```kotlin val Start = TooltipAnchorPosition(5) ``` -------------------------------- ### ModalNavigationDrawer Sample Implementation Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/ModalNavigationDrawer/examples.md A complete example demonstrating how to use ModalNavigationDrawer with a list of navigation items. It shows how to manage the drawer state, handle item clicks, and integrate with other UI elements. ```kotlin @Preview @Composable fun ModalNavigationDrawerSample() { val drawerState = rememberDrawerState(DrawerValue.Closed) val scope = rememberCoroutineScope() val focusRequester = remember { FocusRequester() } // icons to mimic drawer destinations val items = listOf( Icons.Default.AccountCircle, Icons.Default.Bookmarks, Icons.Default.CalendarMonth, Icons.Default.Dashboard, Icons.Default.Email, Icons.Default.Favorite, Icons.Default.Group, Icons.Default.Headphones, Icons.Default.Image, Icons.Default.JoinFull, Icons.Default.Keyboard, Icons.Default.Laptop, Icons.Default.Map, Icons.Default.Navigation, Icons.Default.Outbox, Icons.Default.PushPin, Icons.Default.QrCode, Icons.Default.Radio, ) val selectedItem = remember { mutableStateOf(items[0]) } ModalNavigationDrawer( drawerState = drawerState, drawerContent = { ModalDrawerSheet(drawerState) { Column(Modifier.verticalScroll(rememberScrollState())) { Spacer(Modifier.height(12.dp)) items.forEach { item -> NavigationDrawerItem( icon = { Icon(item, contentDescription = null) }, label = { Text(item.name.substringAfterLast(".")) }, selected = item == selectedItem.value, onClick = { scope.launch { drawerState.close() } selectedItem.value = item }, modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding), ) } } } }, content = { Column( modifier = Modifier.fillMaxSize().padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Text(text = if (drawerState.isClosed) ">>> Swipe >>>" else "<<< Swipe <<<") Spacer(Modifier.height(20.dp)) Button( modifier = Modifier.focusRequester(focusRequester), onClick = { scope.launch { drawerState.open() } }, ) { Text("Click to open") } } }, ) LaunchedEffect(drawerState.isClosed) { if (drawerState.isClosed) { // Keyboard focus should go back to button once drawer closes. focusRequester.requestFocus() } } } ``` -------------------------------- ### FancyTab Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/Tab/examples.md An example of a custom Tab implementation. ```APIDOC ## FancyTab ### Description An example of a custom Tab implementation that displays a title and a decorative element. ### Usage ```kotlin @Composable fun FancyTab(title: String, onClick: () -> Unit, selected: Boolean) { Tab(selected, onClick) { Column( Modifier.padding(10.dp).height(50.dp).fillMaxWidth(), verticalArrangement = Arrangement.SpaceBetween, ) { Box( Modifier.size(10.dp) .align(Alignment.CenterHorizontally) .background( color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.background ) ) Text( text = title, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.align(Alignment.CenterHorizontally), ) } } } ``` ``` -------------------------------- ### FullScreenSearchBarScaffoldSample Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/AppBarWithSearch/examples.md Demonstrates a full-screen search bar integrated into a Scaffold. This example shows how to manage the search bar's state, colors, and content, including handling search results and collapsing the search bar. ```kotlin import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Scaffold import androidx.compose.material3.SearchBarDefaults import androidx.compose.material3.Text import androidx.compose.material3.TextFieldState import androidx.compose.material3.clearAndSetSemantics import androidx.compose.material3.rememberTextFieldState import androidx.compose.material3.windowsize.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.compose.material3.AppBarWithSearch import com.example.compose.material3.ExpandedFullScreenContainedSearchBar import com.example.compose.material3.SampleActions import com.example.compose.material3.SampleLeadingIcon import com.example.compose.material3.SampleNavigationIcon import com.example.compose.material3.SampleSearchResults import com.example.compose.material3.SampleTrailingIcon import com.example.compose.material3.rememberContainedSearchBarState import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Preview @Composable fun FullScreenSearchBarScaffoldSample() { val textFieldState = rememberTextFieldState() val searchBarState = rememberContainedSearchBarState() val scope = rememberCoroutineScope() val scrollBehavior = SearchBarDefaults.enterAlwaysSearchBarScrollBehavior() val appBarWithSearchColors = SearchBarDefaults.appBarWithSearchColors( searchBarColors = SearchBarDefaults.containedColors(state = searchBarState) ) val inputField = @Composable { SearchBarDefaults.InputField( textFieldState = textFieldState, searchBarState = searchBarState, colors = appBarWithSearchColors.searchBarColors.inputFieldColors, onSearch = { scope.launch { searchBarState.animateToCollapsed() } }, placeholder = { Text(modifier = Modifier.clearAndSetSemantics {}, text = "Search") }, leadingIcon = { SampleLeadingIcon(searchBarState, scope) }, trailingIcon = { SampleTrailingIcon() }, ) } Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { AppBarWithSearch( scrollBehavior = scrollBehavior, state = searchBarState, colors = appBarWithSearchColors, inputField = inputField, navigationIcon = { SampleNavigationIcon(searchBarState, isAnimated = true) }, actions = { SampleActions(searchBarState, isAnimated = true) }, ) ExpandedFullScreenContainedSearchBar( state = searchBarState, inputField = inputField, colors = appBarWithSearchColors.searchBarColors, ) { SampleSearchResults( onResultClick = { textFieldState.setTextAndPlaceCursorAtEnd(it) scope.launch { searchBarState.animateToCollapsed() } } ) } }, ) { LazyColumn(contentPadding = it, verticalArrangement = Arrangement.spacedBy(8.dp)) { val list = List(100) { "Text $it" } items(count = list.size) { Text( text = list[it], modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), ) } } } } ``` -------------------------------- ### Set Selection Function Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/interfaces/DateRangePickerState Sets the start and end dates for the selection. Throws IllegalArgumentException if dates are invalid (e.g., start after end, end without start, outside year range). ```kotlin fun setSelection( @Suppress("AutoBoxing") startDateMillis: Long?, @Suppress("AutoBoxing") endDateMillis: Long?, ) ``` -------------------------------- ### PlainTooltip with Caret Start of Anchor Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/TooltipBox/api.md Illustrates a PlainTooltip positioned at the start of its anchor. This is typically used in layouts where 'start' refers to the beginning of the reading direction (e.g., left in LTR languages). ```kotlin import androidx.compose.foundation.Icon import androidx.compose.foundation.IconButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.PlainTooltip import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.material3.TooltipBox import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.rememberTooltipState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.paneTitle import androidx.compose.ui.semantics.semantics @OptIn(ExperimentalMaterial3Api::class) @Composable fun PlainTooltipWithCaretStartOfAnchor() { TooltipBox( positionProvider = TooltipDefaults.rememberTooltipPositionProvider(TooltipAnchorPosition.Start), tooltip = { PlainTooltip( modifier = Modifier.semantics { // TODO(b/496338253): Remove this modifier once bug where tooltip text is // not announced by a11y screen readers is resolved. liveRegion = LiveRegionMode.Assertive paneTitle = "Add to favorites" }, caretShape = TooltipDefaults.caretShape(), ) { Text("Add to favorites") } }, state = rememberTooltipState(), ) { IconButton(onClick = { /* Icon button's click event */ }) { Icon(imageVector = Icons.Filled.Favorite, contentDescription = "Localized Description") } } } ``` -------------------------------- ### Simple SearchBar Implementation Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/SearchBar/api.md Demonstrates a basic implementation of the SearchBar with input field, search action, and placeholder. Includes expanded full-screen search functionality. ```kotlin import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Search import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch @Preview @Composable fun SimpleSearchBarSample() { val searchBarState = rememberSearchBarState() val textFieldState = rememberTextFieldState() val scope = rememberCoroutineScope() val inputField = @Composable { SearchBarDefaults.InputField( textFieldState = textFieldState, searchBarState = searchBarState, onSearch = { scope.launch { searchBarState.animateToCollapsed() } }, placeholder = { Text(modifier = Modifier.clearAndSetSemantics {}, text = "Search") }, leadingIcon = { SampleLeadingIcon(searchBarState, scope) }, trailingIcon = { SampleTrailingIcon() }, ) } SearchBar(state = searchBarState, inputField = inputField) ExpandedFullScreenSearchBar(state = searchBarState, inputField = inputField) { SampleSearchResults( onResultClick = { textFieldState.setTextAndPlaceCursorAtEnd(it) scope.launch { searchBarState.animateToCollapsed() } } ) } } @Composable private fun SampleLeadingIcon( searchBarState: SearchBarState, scope: CoroutineScope ) { if (searchBarState.isCollapsed) { Icon(Icons.Default.Search, contentDescription = "Search") } else { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Back", modifier = Modifier.clickable { scope.launch { searchBarState.animateToExpanded() } } ) } } @Composable private fun SampleTrailingIcon() { Icon(Icons.Default.MoreVert, contentDescription = "More options") } @Composable private fun SampleSearchResults( modifier: Modifier = Modifier, onResultClick: (String) -> Unit ) { val results = remember { listOf("Result 1", "Result 2", "Result 3") } LazyColumn(modifier = modifier.fillMaxSize().padding(16.dp)) { items(results) { Text( text = it, modifier = Modifier .fillParentMaxWidth() .clickable { onResultClick(it) } .padding(vertical = 16.dp) ) } } } ``` -------------------------------- ### Simple OutlinedTextField Example Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/OutlinedTextField/examples.md A basic example of an OutlinedTextField with a label and single-line limit. ```kotlin import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextFieldLineLimits import androidx.compose.material3.rememberTextFieldState import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview @Preview @Composable fun SimpleOutlinedTextFieldSample() { OutlinedTextField( state = rememberTextFieldState(), lineLimits = TextFieldLineLimits.SingleLine, label = { Text("Label") }, ) } ``` -------------------------------- ### Basic TimePicker Sample Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/components/TimePicker Demonstrates a basic TimePicker implementation. Use this for standard time selection scenarios. ```kotlin import androidx.compose.foundation.layout.Box import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TimePicker import androidx.compose.material3.TimePickerDialog import androidx.compose.material3.TimePickerDialogDefaults import androidx.compose.material3.TimePickerDisplayMode import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale @OptIn(ExperimentalMaterial3Api::class) @Composable @Preview fun TimePickerSample() { var showTimePicker by remember { mutableStateOf(false) } val state = rememberTimePickerState() val formatter = remember { SimpleDateFormat("hh:mm a", Locale.getDefault()) } val snackState = remember { SnackbarHostState() } val snackScope = rememberCoroutineScope() Box(propagateMinConstraints = false) { Button(modifier = Modifier.align(Alignment.Center), onClick = { showTimePicker = true }) { Text("Set Time") } SnackbarHost(hostState = snackState) } if (showTimePicker) { TimePickerDialog( title = { TimePickerDialogDefaults.Title(displayMode = TimePickerDisplayMode.Picker) }, onDismissRequest = { showTimePicker = false }, confirmButton = { TextButton( enabled = state.isInputValid, onClick = { state.isHourInputValid val cal = Calendar.getInstance() cal.set(Calendar.HOUR_OF_DAY, state.hour) cal.set(Calendar.MINUTE, state.minute) cal.isLenient = false snackScope.launch { snackState.showSnackbar("Entered time: ${formatter.format(cal.time)}") } showTimePicker = false }, ) { Text("Ok") } }, dismissButton = { TextButton(onClick = { showTimePicker = false }) { Text("Cancel") } }, modeToggleButton = {}, ) { TimePicker(state = state) } } } ``` -------------------------------- ### FloatingToolbarExitDirection Start Property Source: https://composables.com/jetpack-compose/androidx.compose.material3/material3/classes/FloatingToolbarExitDirection/api.md Represents the direction for a FloatingToolbar to exit towards the start of the screen. ```kotlin val Start = FloatingToolbarExitDirection(2) ```