Skip to main content

How to Create a Bottom Sheet in Jetpack Compose

How to Create a Bottom Sheet in Jetpack Compose

How to Create a Bottom Sheet in Jetpack Compose

In modern Android app development, delivering intuitive and engaging user interfaces is essential. One effective UI pattern is the Bottom Sheet, which provides a way to present additional content or actions without navigating away from the current screen. With Jetpack Compose, Android's modern toolkit for building native UI, implementing Bottom Sheets has become easier and more streamlined. This post will guide you through creating Bottom Sheets in Jetpack Compose using Kotlin and Material3 components.

What is a Bottom Sheet?

A Bottom Sheet is a material design component that slides up from the bottom of the screen to reveal more information or actions. It typically appears in two forms:

  • Modal Bottom Sheet: Temporarily displays content and blocks interaction with the rest of the app until it's dismissed.
  • Persistent Bottom Sheet: Remains visible alongside the main content, often used for quick actions or additional options.

Jetpack Compose offers tools to create both variants seamlessly with customizable behavior and appearance.

Getting Started with Bottom Sheets in Jetpack Compose

Before diving into implementation, ensure your project is set up with the latest Compose and Material3 dependencies. Add these to your build.gradle file for Compose and Material3 support:


implementation "androidx.compose.material3:material3:1.1.0"
implementation "androidx.compose.material:material:1.4.0"

With dependencies in place, we can explore how to create Bottom Sheets.

Creating a Modal Bottom Sheet

Modal Bottom Sheets temporarily overlay your app's content and block user interaction with other UI elements until dismissed. Jetpack Compose provides ModalBottomSheet and ModalBottomSheetLayout composables to support this type of sheet.

Here’s how to implement a simple modal bottom sheet:


import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ModalBottomSheetExample() {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val scope = rememberCoroutineScope()
    var showSheet by remember { mutableStateOf(false) }
    
    if (showSheet) {
        ModalBottomSheet(
            onDismissRequest = { showSheet = false },
            sheetState = sheetState,
            dragHandle = { DragHandle() },
            tonalElevation = 8.dp
        ) {
            // Content inside the bottom sheet
            Text(
                text = "Hello from Modal Bottom Sheet!",
                modifier = Modifier.padding(16.dp),
                style = MaterialTheme.typography.bodyLarge
            )
        }
    }
    
    // Main screen content
    Scaffold(
        topBar = {
            SmallTopAppBar(
                title = { Text("Modal Bottom Sheet Demo") }
            )
        },
        content = { paddingValues ->
            Button(
                onClick = { showSheet = true },
                modifier = Modifier.padding(paddingValues).padding(16.dp)
            ) {
                Text("Show Bottom Sheet")
            }
        }
    )
}

Explanation:

  • rememberModalBottomSheetState creates a state object controlling sheet visibility and behavior.
  • ModalBottomSheet composable displays the sheet when showSheet is true.
  • The sheet content can be customized inside the lambda passed to ModalBottomSheet.
  • A button toggles the visibility of the sheet.

Adding a Drag Handle

A nice UX addition is adding a drag handle, a small visual indicator at the top of the sheet to help users understand it can be dragged.


@Composable
fun DragHandle() {
    Box(
        modifier = Modifier
            .padding(vertical = 8.dp)
            .size(width = 40.dp, height = 4.dp)
            .background(
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                shape = MaterialTheme.shapes.extraSmall
            )
            .align(Alignment.CenterHorizontally)
    )
}

This composable can be passed to the dragHandle parameter of ModalBottomSheet for a consistent visual cue.

Creating a Persistent Bottom Sheet

Unlike modal sheets, persistent bottom sheets stay visible and interactable alongside the app's content. While Jetpack Compose does not have an out-of-the-box persistent sheet component like BottomSheetBehavior in the View system, you can easily create a custom version using Swipeable behavior or conditional layouts.

Here's a simple example using a Column with a sliding sheet at the bottom:


import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.roundToInt

@Composable
fun PersistentBottomSheetExample() {
    var sheetOffset by remember { mutableStateOf(0f) }

    Box(modifier = Modifier.fillMaxSize()) {
        // Main content area
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
                .padding(16.dp)
        ) {
            Text(
                text = "Main Content Here",
                style = MaterialTheme.typography.headlineMedium
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "Swipe up the sheet below to see more.",
                style = MaterialTheme.typography.bodyMedium
            )
        }

        // Persistent Bottom Sheet
        val maxSheetHeight = 300.dp
        val minSheetHeight = 80.dp

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .heightIn(min = minSheetHeight, max = maxSheetHeight)
                .offset { androidx.compose.ui.unit.IntOffset(0, sheetOffset.roundToInt()) }
                .background(MaterialTheme.colorScheme.primaryContainer)
                .pointerInput(Unit) {
                    detectVerticalDragGestures { change, dragAmount ->
                        change.consume()
                        sheetOffset = (sheetOffset + dragAmount).coerceIn(
                            -(maxSheetHeight.toPx()),
                            0f
                        )
                    }
                }
                .padding(16.dp)
        ) {
            Column {
                Text(
                    text = "Persistent Bottom Sheet",
                    fontSize = 20.sp,
                    color = MaterialTheme.colorScheme.onPrimaryContainer
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "Drag me up or down!",
                    color = MaterialTheme.colorScheme.onPrimaryContainer
                )
            }
        }
    }
}

Note: The above example is a simple touch-based drag mechanism. For complex interactions, you might want to explore Jetpack Compose's Swipeable modifier with anchors or integrate with BottomSheetScaffold.

Using BottomSheetScaffold for Seamless Integration

Jetpack Compose provides BottomSheetScaffold — a layout composable that integrates a scaffold with a bottom sheet component offering smooth gestures and sheet management.

Here’s a practical example:


import androidx.compose.material.BottomSheetScaffold
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.rememberBottomSheetScaffoldState
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterialApi::class, ExperimentalMaterial3Api::class)
@Composable
fun BottomSheetScaffoldExample() {
    val scaffoldState = rememberBottomSheetScaffoldState()
    val scope = rememberCoroutineScope()

    BottomSheetScaffold(
        scaffoldState = scaffoldState,
        sheetContent = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Text("This is a BottomSheetScaffold content")
                Spacer(modifier = Modifier.height(8.dp))
                Button(onClick = {
                    scope.launch {
                        scaffoldState.bottomSheetState.collapse()
                    }
                }) {
                    Text("Collapse Sheet")
                }
            }
        },
        sheetPeekHeight = 0.dp,
        topBar = {
            CenterAlignedTopAppBar(
                title = { Text("BottomSheetScaffold Demo") }
            )
        }
    ) { innerPadding ->
        Column(modifier = Modifier.padding(innerPadding)) {
            Button(
                onClick = {
                    scope.launch {
                        if (scaffoldState.bottomSheetState.isCollapsed) {
                            scaffoldState.bottomSheetState.expand()
                        } else {
                            scaffoldState.bottomSheetState.collapse()
                        }
                    }
                },
                modifier = Modifier.padding(16.dp)
            ) {
                Text("Toggle Bottom Sheet")
            }
        }
    }
}

The BottomSheetScaffold handles all the heavy lifting: gestures, animations, and layout positioning, allowing you to focus on the sheet content.

Tips for a Better Bottom Sheet Experience

  • Use Material3 Components: Jetpack Compose's Material3 components ensure your Bottom Sheet fits modern design guidelines and theming.
  • Make Content Scrollable: If your bottom sheet’s content can expand beyond the screen, embed scrollable containers like LazyColumn.
  • Accessibility: Ensure the bottom sheet is accessible by providing semantic labeling and focus management.
  • Performance: Avoid heavy recompositions inside your sheet to maintain smooth animations and user experience.

Conclusion

Bottom Sheets are powerful UI components for presenting contextual content without interrupting the main user flow. Jetpack Compose modernizes Bottom Sheet creation by offering flexible composables like ModalBottomSheet and BottomSheetScaffold that tap into Material3 design principles.

Whether you choose a modal or persistent bottom sheet, Compose makes customization, animation, and interaction straightforward. Start integrating Bottom Sheets today to enhance your Android apps with sleek, user-friendly design patterns!

Happy coding! 🚀

Comments

Popular posts from this blog

How to Download Apk file from Url and Install Programmatically

In this post we learn about download apk file from server or website and then install it Programmatically in Phone. Sometimes we have to download external apk file from server and then install if downloading successfully finished.For this we use AsyncTask class  for background process. So here is Code Snippet for this task.Lets Start :- Before this we have to add these Permissions in Manifest.xml file : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> DownloadNewVersion.java class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); bar = new ProgressDialog(getActivity()); bar.setCancelable(false); bar.setMessage("Downl...

Working with Android 11 (Changes and Security Features)

 Hello everyone , I am here with new article which is hot topic nowadays "Android 11" .The stable version of Android.  Android 11 is the eleventh major release and 18th version of Android, the mobile operating system developed by the Open Handset Alliance led by Google. It was released on September 8, 2020.It is comes with many security features and other features as well . And it is now compulsory in play store  to upload new apps with API lavel 30 which is compatible with Android 11 and from November onwards old apps also have to update with API 30 .Some other guidelines you can check out from here . Play Store Guidelines So its clear that we have to update our apps with API level 30 .But Android 11 comes with some changes as well which we have to do in our projects. For example from Android developer site "Android 11 (API level 30) further enhances the platform, giving better protection to app and user data on external storage. ". Scoped storage enforcement: Apps...

How to sort a list in ascending order and Add header by the first letter in the RecyclerView in Android

Hello Forks ! Hope you are doing well. In this tutorial we will understand how to sort a list of data, it could be any data like bank names , places names etc. in ascending order with a header which grouped the same type of data under it. For example we have a list of banks data and we want to group all banks starting with 'A' character in single unit and so on. So without taking too much time  let's move to the coding part and understand how we can achieve this. Step 1 : Create a Model class Named Bank.java public class Bank { private String name; public Bank (String name) { this .name = name; } public String getName () { return name; } } Step 2 : Sort the List of Banks with this Method import java.util.Collections; import java.util.Comparator; import java.util.List; public void sortBankList (List<Bank> bankList) { Collections.sort(bankList, new Comparator <Bank>() { @Override pub...