In kotlin android development with jetpack compose, how a code with Scaffold and…
- User
In kotlin android development with jetpack compose, how a code with Scaffold and navigation-compose would look like
- Assistant
Sure! Below is a comprehensive example of how to use
Scaffoldin combination withnavigation-composeto create a simple Android application using Kotlin and Jetpack Compose. This example includes a top app bar, bottom navigation, and navigation between different screens.Overview
- Dependencies: Ensure you have the necessary dependencies in your
build.gradle. - Navigation Setup: Define your navigation routes.
- Scaffold Structure: Implement
ScaffoldwithTopAppBarandBottomNavigation. - Composable Screens: Create individual composable functions for each screen.
1. Add Necessary Dependencies
First, ensure that your
build.gradle(app level) includes the required dependencies for Jetpack Compose and Navigation.// build.gradle (app level) plugins { id 'com.android.application' id 'kotlin-android' } android { compileSdk 33 defaultConfig { applicationId "com.example.scaffoldnavigation" minSdk 21 targetSdk 33 versionCode 1 versionName "1.0" } buildFeatures { compose true } composeOptions { kotlinCompilerExtensionVersion "1.4.4" } kotlinOptions { jvmTarget = '1.8' } } dependencies { implementation "androidx.core:core-ktx:1.10.1" implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.6.1" implementation "androidx.activity:activity-compose:1.7.2" implementation "androidx.compose.ui:ui:1.4.3" implementation "androidx.compose.material:material:1.4.3" implementation "androidx.compose.ui:ui-tooling-preview:1.4.3" implementation "androidx.navigation:navigation-compose:2.6.0" // Optional: For Preview annotations debugImplementation "androidx.compose.ui:ui-tooling:1.4.3" }2. Define Navigation Routes
Create a sealed class to represent the different screens/routes in your application.
// NavRoutes.kt package com.example.scaffoldnavigation sealed class NavRoutes(val route: String, val title: String, val icon: androidx.compose.material.icons.Icons) { object Home : NavRoutes("home", "Home", androidx.compose.material.icons.Icons.Filled.Home) object Profile : NavRoutes("profile", "Profile", androidx.compose.material.icons.Icons.Filled.Person) object Settings : NavRoutes("settings", "Settings", androidx.compose.material.icons.Icons.Filled.Settings) }3. Implement the Scaffold with Navigation
Now, set up the
Scaffoldwith aTopAppBarandBottomNavigation. TheNavHostmanages the navigation between different composable screens.// MainActivity.kt package com.example.scaffoldnavigation import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.padding import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Settings import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.navigation.NavDestination import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.* class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Setting the content of the activity setContent { MyApp() } } } @Composable fun MyApp() { // Create a NavController val navController = rememberNavController() // Define the Scaffold Scaffold( topBar = { TopAppBar( title = { // Display the title based on the current destination val currentRoute = currentRoute(navController) Text(text = currentRoute?.title ?: "App") } ) }, bottomBar = { BottomNavigationBar(navController = navController) } ) { innerPadding -> // NavHost manages the navigation graph NavHost( navController = navController, startDestination = NavRoutes.Home.route, modifier = Modifier.padding(innerPadding) ) { composable(NavRoutes.Home.route) { HomeScreen() } composable(NavRoutes.Profile.route) { ProfileScreen() } composable(NavRoutes.Settings.route) { SettingsScreen() } } } } // Function to get the current route @Composable fun currentRoute(navController: NavHostController): NavRoutes? { val navBackStackEntry by navController.currentBackStackEntryAsState() val route = navBackStackEntry?.destination?.route return when (route) { NavRoutes.Home.route -> NavRoutes.Home NavRoutes.Profile.route -> NavRoutes.Profile NavRoutes.Settings.route -> NavRoutes.Settings else -> null } } @Composable fun BottomNavigationBar(navController: NavHostController) { val items = listOf( NavRoutes.Home, NavRoutes.Profile, NavRoutes.Settings ) BottomNavigation { val currentRoute = currentRoute(navController) items.forEach { screen -> BottomNavigationItem( icon = { Icon(screen.icon, contentDescription = screen.title) }, label = { Text(screen.title) }, selected = currentRoute == screen, onClick = { navController.navigate(screen.route) { // Pop up to the start destination of the graph to // avoid building up a large stack of destinations popUpTo(navController.graph.findStartDestination().id) { saveState = true } // Avoid multiple copies of the same destination launchSingleTop = true // Restore state when reselecting a previously selected item restoreState = true } } ) } } }4. Create Composable Screens
Define the individual screens that will be navigated to. Each screen is a composable function.
// HomeScreen.kt package com.example.scaffoldnavigation import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun HomeScreen() { // Sample content for Home Screen Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Text(text = "Home Screen", style = MaterialTheme.typography.h4) } } // ProfileScreen.kt package com.example.scaffoldnavigation import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun ProfileScreen() { // Sample content for Profile Screen Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Text(text = "Profile Screen", style = MaterialTheme.typography.h4) } } // SettingsScreen.kt package com.example.scaffoldnavigation import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun SettingsScreen() { // Sample content for Settings Screen Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Text(text = "Settings Screen", style = MaterialTheme.typography.h4) } }5. (Optional) Preview the Composables
You can add preview annotations to see your composables in Android Studio's Preview pane.
// Preview.kt package com.example.scaffoldnavigation import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview @Preview(showBackground = true) @Composable fun HomeScreenPreview() { HomeScreen() } @Preview(showBackground = true) @Composable fun ProfileScreenPreview() { ProfileScreen() } @Preview(showBackground = true) @Composable fun SettingsScreenPreview() { SettingsScreen() }Complete Project Structure
For clarity, here's how the project structure looks:
app/ ├─ src/ │ ├─ main/ │ │ ├─ java/com/example/scaffoldnavigation/ │ │ │ ├─ MainActivity.kt │ │ │ ├─ NavRoutes.kt │ │ │ ├─ HomeScreen.kt │ │ │ ├─ ProfileScreen.kt │ │ │ ├─ SettingsScreen.kt │ │ │ ├─ Preview.kt │ │ ├─ res/ │ │ │ ├─ ... (other resources) │ ├─ ... (other source sets)Explanation
-
MainActivity:
- Sets up the
Scaffoldwhich includes aTopAppBarand aBottomNavigationBar. - Uses
NavHostto manage navigation between different composable screens. - The
modifier = Modifier.padding(innerPadding)ensures that the content doesn't go underneath theTopAppBarandBottomNavigationBar.
- Sets up the
-
Navigation:
NavHostdefines the navigation graph withcomposabledestinations.- The
BottomNavigationBardisplays navigation items and handles navigation actions.
-
Current Route:
- The
currentRoutefunction retrieves the current route from theNavControllerto update theTopAppBartitle and highlight the selected item in theBottomNavigation.
- The
-
Composable Screens:
- Each screen (
HomeScreen,ProfileScreen,SettingsScreen) is a simple composable that displays centered text. You can customize these screens as per your app's requirements.
- Each screen (
Running the App
When you run the app, you'll see:
- A TopAppBar displaying the title of the current screen.
- A BottomNavigation with three items: Home, Profile, and Settings.
- Tapping on each bottom navigation item navigates to the corresponding screen, and the title in the
TopAppBarupdates accordingly.
Additional Enhancements
- Icons: Customize icons for each navigation item by updating the
NavRoutessealed class with different icons. - Passing Parameters: Use Navigation arguments to pass data between screens.
- Animations: Add animations between screen transitions using
AnimatedNavHostfrom Accompanist or other animation libraries. - State Management: Integrate with
ViewModelfor managing UI-related data.
This example serves as a foundational template to build more complex applications using Jetpack Compose's
Scaffoldandnavigation-compose. Feel free to expand upon it to suit your specific needs! - Dependencies: Ensure you have the necessary dependencies in your