### Automated Text Replacement in Linux Source: https://github.com/google/accompanist/blob/main/docs/migration.md This command-line script utilizes `find` and `sed` to perform a project-wide search and replace for 'dev.chrisbanes.accompanist' with 'com.google.accompanist' in Kotlin and Gradle files on Linux systems. It's recommended to back up your project before running. ```bash find . -type f ( -name '*.kt' -or -name '*.gradle*' ) \ -exec sed -i 's/dev\.chrisbanes\.accompanist/com\.google\.accompanist/' {} \; ``` -------------------------------- ### Automated Text Replacement in macOS Source: https://github.com/google/accompanist/blob/main/docs/migration.md This command-line script uses `find` and `sed` to automatically replace all occurrences of 'dev.chrisbanes.accompanist' with 'com.google.accompanist' in Kotlin and Gradle files within the current directory on macOS. Ensure you have backups before execution. ```bash find . -type f ( -name '*.kt' -or -name '*.gradle*' ) \ -exec sed -i '' 's/dev\.chrisbanes\.accompanist/com\.google\.accompanist/' {} \; ``` -------------------------------- ### Apply Code Formatting with Spotless Source: https://github.com/google/accompanist/blob/main/CONTRIBUTING.md This command applies code formatting according to the project's specifications using Spotless. Running this command ensures that all code adheres to the established style guide, making contributions more uniform and readable. It targets the 'pager' module specifically. ```bash ./gradlew :pager:spotlessApply ``` -------------------------------- ### Implement Responsive Two-Pane Layout Strategy Source: https://context7.com/google/accompanist/llms.txt Dynamically switches between horizontal and vertical two-pane layouts based on screen orientation. This example uses a custom `TwoPaneStrategy` that checks screen dimensions to determine the split orientation and fraction. ```kotlin import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.google.accompanist.adaptive.TwoPane import com.google.accompanist.adaptive.TwoPaneStrategy import com.google.accompanist.adaptive.HorizontalTwoPaneStrategy import com.google.accompanist.adaptive.VerticalTwoPaneStrategy import com.google.accompanist.adaptive.FoldAwareConfiguration import com.google.accompanist.adaptive.calculateDisplayFeatures import android.app.Activity @Composable fun ResponsiveTwoPaneExample(activity: Activity) { val displayFeatures = calculateDisplayFeatures(activity) TwoPane( first = { // Navigation or list content NavigationRail { NavigationRailItem( selected = true, onClick = { }, icon = { Icon(Icons.Default.Home, "Home") }, label = { Text("Home") } ) } }, second = { // Main content area LazyColumn(modifier = Modifier.fillMaxSize()) { items(20) { index -> ListItem( headlineContent = { Text("Item $index") } ) } } }, strategy = TwoPaneStrategy { density, layoutDirection, layoutCoordinates -> // Adapt strategy based on dimensions if (layoutCoordinates.size.height >= layoutCoordinates.size.width) { // Portrait: split vertically VerticalTwoPaneStrategy( splitFraction = 0.3f, gapHeight = 8.dp ) } else { // Landscape: split horizontally HorizontalTwoPaneStrategy( splitFraction = 0.25f, gapWidth = 8.dp ) }.calculateSplitResult(density, layoutDirection, layoutCoordinates) }, displayFeatures = displayFeatures, foldAwareConfiguration = FoldAwareConfiguration.AllFolds, modifier = Modifier.fillMaxSize() ) } ``` -------------------------------- ### Basic MaterialTheme Setup in Jetpack Compose Source: https://github.com/google/accompanist/blob/main/docs/appcompat-theme.md This snippet illustrates the fundamental structure of theming in Jetpack Compose using `MaterialTheme`. It shows how to provide custom instances for `typography`, `colors`, and `shapes` to define the overall look and feel of the Compose UI. This serves as a baseline for Compose theming before integrating with AppCompat. ```kotlin MaterialTheme( typography = type, colors = colors, shapes = shapes ) { // Surface, Scaffold, etc } ``` -------------------------------- ### Fixed Offset Two-Pane Layout Example (Kotlin) Source: https://context7.com/google/accompanist/llms.txt Demonstrates creating a two-pane layout where the first pane has a fixed width. This is useful for navigation drawers or sidebars. It utilizes HorizontalTwoPaneStrategy with a specified split offset. Dependencies include Jetpack Compose Material and Accompanist. ```kotlin import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.window.layout.DisplayFeature import com.google.accompanist.adaptive.HorizontalTwoPaneStrategy import com.google.accompanist.adaptive.TwoPane import com.google.accompanist.adaptive.FoldAwareConfiguration // Assume calculateDisplayFeatures and Activity are defined elsewhere @Composable fun FixedOffsetTwoPaneExample(activity: Activity) { val displayFeatures = calculateDisplayFeatures(activity) TwoPane( first = { // Fixed width navigation drawer Surface( color = MaterialTheme.colorScheme.surfaceVariant, modifier = Modifier.fillMaxSize() ) { Column(modifier = Modifier.padding(16.dp)) { Text("Navigation", style = MaterialTheme.typography.headlineMedium) Spacer(modifier = Modifier.height(16.dp)) repeat(5) { TextButton(onClick = { }) { Text("Menu Item ${it + 1}") } } } } }, second = { // Main content fills remaining space Surface(modifier = Modifier.fillMaxSize()) { Column(modifier = Modifier.padding(24.dp)) { Text("Main Content", style = MaterialTheme.typography.headlineLarge) Spacer(modifier = Modifier.height(24.dp)) Text("Content area that adapts to available space") } } }, strategy = HorizontalTwoPaneStrategy( splitOffset = 280.dp, // Fixed width for first pane offsetFromStart = true, gapWidth = 1.dp ), displayFeatures = displayFeatures, foldAwareConfiguration = FoldAwareConfiguration.VerticalFoldsOnly, modifier = Modifier.fillMaxSize() ) } ``` -------------------------------- ### Vertical Two-Pane Layout Example (Kotlin) Source: https://context7.com/google/accompanist/llms.txt Illustrates a vertical split for master-detail UIs in portrait mode. The content is divided into a top pane for a list and a bottom pane for details. It uses VerticalTwoPaneStrategy to define the split fraction. Dependencies include Jetpack Compose Material, LazyColumn, and Accompanist. ```kotlin import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme 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.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.window.layout.DisplayFeature import com.google.accompanist.adaptive.VerticalTwoPaneStrategy import com.google.accompanist.adaptive.TwoPane import com.google.accompanist.adaptive.FoldAwareConfiguration // Assume calculateDisplayFeatures and Activity are defined elsewhere @Composable fun VerticalTwoPaneExample(activity: Activity) { val displayFeatures = calculateDisplayFeatures(activity) var selectedItem by remember { mutableStateOf(0) } TwoPane( first = { // Top pane - scrollable list LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp) ) { items(15) { Card( onClick = { selectedItem = it }, modifier = Modifier .fillMaxWidth() .padding(vertical = 4.dp) ) { Row( modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Icon(Icons.Default.Email, "Email") Spacer(modifier = Modifier.width(16.dp)) Column { Text("Email ${it + 1}", fontWeight = FontWeight.Bold) Text("Preview text...", style = MaterialTheme.typography.bodySmall) } } } } } }, second = { // Bottom pane - detail view Card( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Column(modifier = Modifier.padding(24.dp)) { Text( "Email ${selectedItem + 1} Details", style = MaterialTheme.typography.headlineMedium ) Spacer(modifier = Modifier.height(16.dp)) Text("Full content of the selected email appears here.") } } }, strategy = VerticalTwoPaneStrategy( splitFraction = 0.4f, // 40% top, 60% bottom gapHeight = 8.dp ), displayFeatures = displayFeatures, foldAwareConfiguration = FoldAwareConfiguration.HorizontalFoldsOnly, modifier = Modifier.fillMaxSize() ) } ``` -------------------------------- ### Update API Signatures with Metalava Source: https://github.com/google/accompanist/blob/main/CONTRIBUTING.md This command updates the API signatures for the project. It's a necessary step when making changes to any public APIs to ensure consistency and correctness. The command requires Gradle to be installed and configured for the project. ```bash ./gradlew metalavaGenerateSignatureRelease ``` -------------------------------- ### AppCompat XML Theme Example Source: https://github.com/google/accompanist/blob/main/docs/appcompat-theme.md This XML snippet displays a typical AppCompat theme style definition. It shows how to set theme attributes like `colorPrimary` and `colorAccent` using color resources. This is the type of theme that the Accompanist library aims to adapt for use in Jetpack Compose. ```xml ``` -------------------------------- ### Customizing AppCompat Theme in Jetpack Compose Source: https://github.com/google/accompanist/blob/main/docs/appcompat-theme.md This example shows how to use `createAppCompatTheme()` to obtain and customize the generated `Colors` and `Typography` instances from the host AppCompat theme before passing them to `MaterialTheme`. This allows for fine-tuning the theme's appearance beyond what's directly available in XML. ```kotlin val context = LocalContext.current var (colors, type) = context.createAppCompatTheme() // Modify colors or type as required. Then pass them // through to MaterialTheme... MaterialTheme( colors = colors, typography = type ) { // rest of layout } ``` -------------------------------- ### Wrap NavHost in ModalBottomSheetLayout Source: https://github.com/google/accompanist/blob/main/docs/navigation-material.md Shows how to wrap the NavHost composable with ModalBottomSheetLayout, passing the BottomSheetNavigator. This setup is necessary to display bottom sheet destinations managed by the navigator. ```kotlin import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.google.accompanist.navigation.material.ModalBottomSheetLayout import com.google.accompanist.navigation.material.rememberBottomSheetNavigator @Composable fun MyApp() { val bottomSheetNavigator = rememberBottomSheetNavigator() val navController = rememberNavController(bottomSheetNavigator) ModalBottomSheetLayout(bottomSheetNavigator) { NavHost(navController, "home") { // Graph definitions go here } } } ``` -------------------------------- ### Replace rememberNavController() with rememberAnimatedNavController() Source: https://github.com/google/accompanist/blob/main/docs/navigation-animation.md This code example illustrates the replacement of `rememberNavController()` with `rememberAnimatedNavController()` for managing navigation state within an animated navigation graph. This change is crucial for enabling animation capabilities. ```kotlin // Replace rememberNavController() with rememberAnimatedNavController() val navController = rememberAnimatedNavController() ``` -------------------------------- ### Define Custom Transitions for Navigation Routes Source: https://github.com/google/accompanist/blob/main/docs/navigation-animation.md This example defines custom enter, exit, pop enter, and pop exit transitions for navigating between 'Red' and 'Blue' routes. It utilizes `slideIntoContainer` and `slideOutOfContainer` with `tween` animation for a smooth visual effect. ```kotlin composable( "Red", enterTransition = { when (initialState.destination.route) { "Blue" -> slideIntoContainer(AnimatedContentScope.SlideDirection.Left, animationSpec = tween(700)) else -> null } }, exitTransition = { when (targetState.destination.route) { "Blue" -> slideOutOfContainer(AnimatedContentScope.SlideDirection.Left, animationSpec = tween(700)) else -> null } }, popEnterTransition = { when (initialState.destination.route) { "Blue" -> slideIntoContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(700)) else -> null } }, popExitTransition = { when (targetState.destination.route) { "Blue" -> slideOutOfContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(700)) else -> null } } ) { RedScreen(navController) } ``` -------------------------------- ### Basic WebView Usage in Jetpack Compose Source: https://github.com/google/accompanist/blob/main/docs/web.md Demonstrates the fundamental implementation of a WebView within a Jetpack Compose layout. It requires remembering the WebView state, typically initialized with a URL. ```kotlin val state = rememberWebViewState("https://example.com") WebView( state ) ``` -------------------------------- ### Configure WebView Settings (e.g., JavaScript) Source: https://github.com/google/accompanist/blob/main/docs/web.md Shows how to configure WebView settings, such as enabling JavaScript, using the `onCreated` callback. This callback provides access to the WebView instance for further customization. ```kotlin WebView( state = webViewState, onCreated = { it.settings.javaScriptEnabled = true } ) ``` -------------------------------- ### Create Two-Pane Adaptive Layouts Source: https://context7.com/google/accompanist/llms.txt Generates responsive layouts that adapt to foldable devices by splitting content across two panes. It utilizes `TwoPane` with a specified `TwoPaneStrategy` and `displayFeatures` to manage the layout. ```kotlin import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.google.accompanist.adaptive.TwoPane import com.google.accompanist.adaptive.HorizontalTwoPaneStrategy import com.google.accompanist.adaptive.calculateDisplayFeatures import android.app.Activity @Composable fun TwoPaneExample(activity: Activity) { // Calculate display features (folds, hinges) val displayFeatures = calculateDisplayFeatures(activity) TwoPane( first = { Card(modifier = Modifier.padding(8.dp)) { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Text("Master Pane - Item List") // List view content } } }, second = { Card(modifier = Modifier.padding(8.dp)) { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Text("Detail Pane - Item Details") // Detail view content } } }, strategy = HorizontalTwoPaneStrategy( splitFraction = 0.5f, gapWidth = 16.dp ), displayFeatures = displayFeatures, modifier = Modifier.fillMaxSize() ) } ``` -------------------------------- ### Configure Gradle Dependencies for Accompanist Modules Source: https://context7.com/google/accompanist/llms.txt Adds Accompanist modules and their required Compose dependencies to an Android project using Gradle. Ensure versions are compatible with your project's Compose UI version. Requires setting `compose_version` and `accompanist_version` in the project's `build.gradle` file. ```groovy // Project build.gradle buildscript { ext { compose_version = '1.7.0' accompanist_version = '0.37.0' } } // Module build.gradle dependencies { // Permissions module implementation "com.google.accompanist:accompanist-permissions:$accompanist_version" // Drawable Painter module implementation "com.google.accompanist:accompanist-drawablepainter:$accompanist_version" // Adaptive layouts module implementation "com.google.accompanist:accompanist-adaptive:$accompanist_version" // Required for adaptive layouts implementation "androidx.window:window:1.3.0" // Compose dependencies implementation "androidx.compose.ui:ui:$compose_version" implementation "androidx.compose.material3:material3:1.3.0" implementation "androidx.activity:activity-compose:1.9.0" } ``` ```kotlin // Kotlin DSL (build.gradle.kts) dependencies { // Permissions implementation("com.google.accompanist:accompanist-permissions:0.37.0") // Drawable Painter implementation("com.google.accompanist:accompanist-drawablepainter:0.37.0") // Adaptive implementation("com.google.accompanist:accompanist-adaptive:0.37.0") implementation("androidx.window:window:1.3.0") } ``` -------------------------------- ### Check Project Build and Tests Source: https://github.com/google/accompanist/blob/main/docs/updating.md Command to verify that the project builds successfully and all tests pass after dependency updates. This ensures the stability of the changes before committing. ```sh ./gradlew check ``` -------------------------------- ### Accompanist WebView Dependency Source: https://github.com/google/accompanist/blob/main/docs/web.md Provides the Maven dependency declaration for the Accompanist WebView library. Ensure you replace `` with the desired version number. ```groovy repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-webview:" } ``` -------------------------------- ### Prepare Next Development Version Source: https://github.com/google/accompanist/blob/main/docs/updating.md Instructions for updating the `VERSION_NAME` property in `gradle.properties` to reflect the next development version, including adding the '-SNAPSHOT' suffix. This is done after a release is finalized. ```sh # Example: released version: `0.3.0`. Update to `0.3.1-SNAPSHOT` git commit and push to `main`. # Finally, merge all of these changes back to `snapshot`: git checkout snapshot && git pull git merge main git push ``` -------------------------------- ### Provide Custom WebView Factory Source: https://github.com/google/accompanist/blob/main/docs/web.md Illustrates how to use a custom `WebView` subclass or gain more control over WebView instantiation by providing a factory lambda. The factory receives a `Context` and should return an instance of `WebView` or its subclass. ```kotlin WebView( ... factory = { context -> CustomWebView(context) } ) ``` -------------------------------- ### Request Single Android Runtime Permission with State Management (Kotlin) Source: https://context7.com/google/accompanist/llms.txt Demonstrates how to request a single Android runtime permission (e.g., CAMERA) using Accompanist Permissions. It includes state management for granted/denied status and a mechanism to show rationale to the user if needed. The `rememberPermissionState` function handles the permission lifecycle and results. ```kotlin @OptIn(ExperimentalPermissionsApi::class) @Composable fun CameraPermissionExample() { // Remember permission state across recompositions val cameraPermissionState = rememberPermissionState( android.Manifest.permission.CAMERA, onPermissionResult = { isGranted -> if (isGranted) { Log.d("Permissions", "Camera permission granted") } else { Log.d("Permissions", "Camera permission denied") } } ) // Check if permission is granted if (cameraPermissionState.status.isGranted) { Text("Camera permission Granted - Ready to use camera") // Camera functionality here } else { Column { // Show rationale if needed val textToShow = if (cameraPermissionState.status.shouldShowRationale) { "The camera is important for this app. Please grant the permission." } else { "Camera permission is required for this feature." } Text(textToShow) Spacer(modifier = Modifier.height(8.dp)) // Request permission on button click Button(onClick = { cameraPermissionState.launchPermissionRequest() }) { Text("Request Camera Permission") } } } } ``` -------------------------------- ### Add Snapshot Repository and Dependency for Compose Snapshots (Groovy) Source: https://github.com/google/accompanist/blob/main/docs/using-snapshot-version.md Sets up the Maven snapshot repository and includes an Accompanist dependency that is specifically built against Jetpack Compose snapshot versions. This is crucial when your project also uses SNAPSHOT versions of Jetpack Compose libraries to avoid version conflicts. ```groovy repositories { // ... maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } } dependencies { // Check the latest SNAPSHOT version from the link above classpath 'com.google.accompanist:accompanist-coil:XXXX.compose-YYYYY-SNAPSHOT' } ``` -------------------------------- ### Replace NavHost with AnimatedNavHost Source: https://github.com/google/accompanist/blob/main/docs/navigation-animation.md This snippet shows the migration from the standard `NavHost` to `AnimatedNavHost`. This change is essential for utilizing the custom enter, exit, popEnter, and popExit transitions provided by Accompanist's navigation animation library. ```kotlin AnimatedNavHost(navController = navController, startDestination = "Home") { composable("Home") { HomeScreen(navController) } composable("Blue") { BlueScreen(navController) } composable("Red") { RedScreen(navController) } } ``` -------------------------------- ### Configure AndroidManifest.xml for Permissions Module Source: https://context7.com/google/accompanist/llms.txt Declares necessary Android runtime permissions within the `AndroidManifest.xml` file for the Accompanist Permissions module. This ensures the application has the required privileges to access features like the camera or location. It also includes a declaration for foldable device sensor support, which is optional. ```xml ``` -------------------------------- ### Add Accompanist Adaptive Dependency (Gradle) Source: https://github.com/google/accompanist/blob/main/adaptive/README.md This code snippet shows how to add the Accompanist adaptive library to your Android project using Gradle. It specifies the mavenCentral repository and the implementation dependency for the adaptive module. Replace `` with the desired library version. ```groovy repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-adaptive:" } ``` -------------------------------- ### Add Snapshot Repository and Dependency (Groovy) Source: https://github.com/google/accompanist/blob/main/docs/using-snapshot-version.md Configures the Maven repository to include snapshots and adds a SNAPSHOT version of an Accompanist library dependency. This is typically used for development or testing with the latest, unreleased versions of Accompanist. ```groovy repositories { // ... maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } } dependencies { // Check the latest SNAPSHOT version from the link above classpath 'com.google.accompanist:accompanist-coil:XXX-SNAPSHOT' } ``` -------------------------------- ### Request Multiple Android Runtime Permissions with Aggregated State (Kotlin) Source: https://context7.com/google/accompanist/llms.txt Illustrates how to request and manage the state of multiple Android runtime permissions simultaneously using Accompanist Permissions. This snippet shows how to track the status of several permissions (e.g., CAMERA, RECORD_AUDIO, ACCESS_FINE_LOCATION) and handle their aggregated results. It provides UI elements to display missing permissions and request them collectively. ```kotlin @OptIn(ExperimentalPermissionsApi::class) @Composable fun MultiplePermissionsExample() { // Remember state for multiple permissions val multiplePermissionsState = rememberMultiplePermissionsState( permissions = listOf( Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION ), onPermissionsResult = { permissionResults -> permissionResults.forEach { (permission, isGranted) -> Log.d("Permissions", "$permission: $isGranted") } } ) // Check if all permissions are granted if (multiplePermissionsState.allPermissionsGranted) { Text("All permissions granted! App fully functional.") } else { Column { // Display revoked permissions val revokedPermissions = multiplePermissionsState.revokedPermissions val permissionText = buildString { append("Missing permissions: ") revokedPermissions.forEachIndexed { index, permissionState -> append(permissionState.permission.substringAfterLast(".")) if (index < revokedPermissions.size - 1) append(", ") } } Text(permissionText) // Show rationale if needed if (multiplePermissionsState.shouldShowRationale) { Text("These permissions are required for full functionality.") } Spacer(modifier = Modifier.height(8.dp)) // Request all permissions at once Button(onClick = { multiplePermissionsState.launchMultiplePermissionRequest() }) { Text("Request Permissions") } } } } ``` -------------------------------- ### Accompanist System UI Controller Dependency Source: https://github.com/google/accompanist/blob/main/docs/systemuicontroller.md This snippet provides the Gradle configuration for adding the Accompanist System UI Controller library to an Android project. It includes the necessary repository declaration and the dependency implementation line, specifying a placeholder for the version. ```groovy repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-systemuicontroller:" } ``` -------------------------------- ### Add Drawable Painter Dependency (Groovy) Source: https://github.com/google/accompanist/blob/main/docs/drawablepainter.md This snippet shows how to add the Drawable Painter library as a dependency to an Android project using Gradle. It specifies the Maven Central repository and the `accompanist-drawablepainter` artifact with a placeholder for the version. This is a build-time configuration. ```groovy repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-drawablepainter:" } ``` -------------------------------- ### Using AppCompat XML Themes in Jetpack Compose Source: https://github.com/google/accompanist/blob/main/docs/appcompat-theme.md This snippet demonstrates how to wrap your Compose UI with `AppCompatTheme` to inherit styling from the Activity's AppCompat XML theme. It automatically reads the host context's theme and applies it to `MaterialTheme`'s colors, shapes, and typography. This is particularly useful for migrating existing apps to Compose. ```kotlin AppCompatTheme { // MaterialTheme.colors, MaterialTheme.shapes, MaterialTheme.typography // will now contain copies of the context's theme } ``` -------------------------------- ### Convert Android Drawables to Compose Painters Source: https://context7.com/google/accompanist/llms.txt Converts Android Drawables into Compose Painters, providing lifecycle management and animation support. It takes a Drawable as input and returns a Painter. Supports animated and color drawables. ```kotlin import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.asComposeRenderNode import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.graphics.drawscope.inset import androidx.compose.ui.graphics.drawscope.withTransform import androidx.compose.ui.graphics.drawscope.DrawTransform import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.graphics.drawscope.clipToBounds import androidx.compose.ui.graphics.drawscope.drawContext import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.drawscope.draw import androidx.compose.ui.graphics.drawscope.drawText import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.resolveDefaults import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.core.content.ContextCompat import com.google.accompanist.drawablepainter.rememberDrawablePainter import com.google.accompanist.adaptive.TwoPane import com.google.accompanist.adaptive.TwoPaneStrategy import com.google.accompanist.adaptive.HorizontalTwoPaneStrategy import com.google.accompanist.adaptive.VerticalTwoPaneStrategy import com.google.accompanist.adaptive.FoldAwareConfiguration import com.google.accompanist.adaptive.calculateDisplayFeatures import android.app.Activity import android.graphics.drawable.ColorDrawable @Composable fun DrawablePainterExample() { val context = LocalContext.current // Load drawable from resources val drawable = ContextCompat.getDrawable(context, R.drawable.ic_launcher) // Convert to Painter with automatic lifecycle management val painter = rememberDrawablePainter(drawable = drawable) Image( painter = painter, contentDescription = "App launcher icon", modifier = Modifier.size(100.dp) ) } @Composable fun AnimatedDrawableExample() { val context = LocalContext.current // Load animated drawable (will automatically start/stop) val animatedDrawable = ContextCompat.getDrawable( context, R.drawable.animated_vector_drawable ) val painter = rememberDrawablePainter(drawable = animatedDrawable) Image( painter = painter, contentDescription = "Animated icon", modifier = Modifier .size(150.dp) .padding(16.dp), contentScale = ContentScale.Fit ) } @Composable fun ColorDrawableExample() { // ColorDrawable is optimized to ColorPainter val colorDrawable = ColorDrawable(android.graphics.Color.RED) val painter = rememberDrawablePainter(drawable = colorDrawable) Box( modifier = Modifier .size(200.dp) .background(Color.White) ) { Image( painter = painter, contentDescription = "Red background", modifier = Modifier.fillMaxSize() ) } } ``` -------------------------------- ### Update Compose SNAPSHOT Build - Git Checkout Source: https://github.com/google/accompanist/wiki/Development These commands are used to create a new branch based off the 'snapshot' branch, allowing for updates to a newer Compose SNAPSHOT build. Ensure you are on the 'snapshot' branch and have pulled the latest changes before creating the new branch. ```shell git checkout snapshot && git pull git checkout -b new-snapshot ``` -------------------------------- ### Add Accompanist Navigation Animation Dependency Source: https://github.com/google/accompanist/blob/main/docs/navigation-animation.md This snippet shows how to add the Accompanist Navigation Animation library to your project's dependencies using Gradle. It specifies the Maven Central repository and the implementation dependency. ```groovy repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-navigation-animation:" } ``` -------------------------------- ### Merge Snapshot into Main Branch Source: https://github.com/google/accompanist/blob/main/docs/updating.md Commands to merge the 'snapshot' branch into the 'main' branch. This is the initial step in preparing for a new release, bringing the latest snapshot changes into the main development line. ```sh git checkout snapshot && git pull git checkout main && git pull # Create branch for PR git checkout -b main_snapshot_merge # Merge in the snapshot branch git merge snapshot ``` -------------------------------- ### Modify System Bar Scrim Logic Source: https://github.com/google/accompanist/blob/main/docs/systemuicontroller.md This code illustrates how to customize the scrim logic when setting the status bar color. It shows a lambda function being passed to `setStatusBarColor` that allows for modification of the requested color, particularly useful for ensuring contrast on older Android versions that might not natively support dark icons. ```kotlin systemUiController.setStatusBarColor( color = Color.Transparent, darkIcons = true ) { requestedColor -> // TODO: return a darkened color to be used when the system doesn't // natively support dark icons } ``` -------------------------------- ### Set System Bar Colors in Jetpack Compose Source: https://github.com/google/accompanist/blob/main/docs/systemuicontroller.md This snippet demonstrates how to use the `rememberSystemUiController()` function to obtain an instance of `SystemUiController` and then update the system bar colors, such as setting them to transparent and controlling dark icon visibility based on the system's dark theme setting. It utilizes `DisposableEffect` to manage the lifecycle of these changes. ```kotlin val systemUiController = rememberSystemUiController() val useDarkIcons = !isSystemInDarkTheme() DisposableEffect(systemUiController, useDarkIcons) { // Update all of the system bar colors to be transparent, and use // dark icons if we're in light theme systemUiController.setSystemBarsColor( color = Color.Transparent, darkIcons = useDarkIcons ) // setStatusBarColor() and setNavigationBarColor() also exist onDispose {} } ``` -------------------------------- ### Replace Navigation Compose with AnimatedNavHost Source: https://github.com/google/accompanist/blob/main/docs/navigation-animation.md This snippet demonstrates how to replace standard Navigation Compose components with their animated equivalents from Accompanist. It shows the necessary import changes for seamless integration of custom navigation animations. ```kotlin import androidx.navigation.compose.navigation import androidx.navigation.compose.composable // To import com.google.accompanist.navigation.animation.navigation import com.google.accompanist.navigation.animation.composable ``` -------------------------------- ### Request Camera Permission with Jetpack Compose Source: https://github.com/google/accompanist/blob/main/docs/permissions.md This snippet demonstrates how to request and manage the state of a single permission (CAMERA) using Jetpack Compose. It checks if the permission is granted, shows rationale if needed, and launches the permission request. The request must be called from a non-composable scope. ```kotlin @OptIn(ExperimentalPermissionsApi::class) @Composable private fun FeatureThatRequiresCameraPermission() { // Camera permission state val cameraPermissionState = rememberPermissionState( android.Manifest.permission.CAMERA ) if (cameraPermissionState.status.isGranted) { Text("Camera permission Granted") } else { Column { val textToShow = if (cameraPermissionState.status.shouldShowRationale) { // If the user has denied the permission but the rationale can be shown, // then gently explain why the app requires this permission "The camera is important for this app. Please grant the permission." } else { // If it's the first time the user lands on this feature, or the user // doesn't want to be asked again for this permission, explain that the // permission is required "Camera permission required for this feature to be available. " + "Please grant the permission" } Text(textToShow) Button(onClick = { cameraPermissionState.launchPermissionRequest() }) { Text("Request permission") } } } } ``` -------------------------------- ### Update Compose Snapshot Branch Source: https://github.com/google/accompanist/blob/main/docs/updating.md Commands to checkout the snapshot branch, pull latest changes, and create a new branch for updating Compose snapshot versions. This is the first step in integrating a new Compose snapshot. ```sh git checkout snapshot && git pull # Create branch for PR git checkout -b update_snapshot ``` -------------------------------- ### Create BottomSheetNavigator and NavController in Compose Source: https://github.com/google/accompanist/blob/main/docs/navigation-material.md Demonstrates how to initialize a BottomSheetNavigator and integrate it with a NavController within a Jetpack Compose application. This is a foundational step for enabling bottom sheet destinations. ```kotlin import androidx.compose.runtime.Composable import androidx.navigation.compose.rememberNavController import com.google.accompanist.navigation.material.rememberBottomSheetNavigator @Composable fun MyApp() { val bottomSheetNavigator = rememberBottomSheetNavigator() val navController = rememberNavController(bottomSheetNavigator) } ``` -------------------------------- ### Define Custom Transitions with AnimatedNavHost in Kotlin Source: https://github.com/google/accompanist/blob/main/docs/navigation-animation.md Demonstrates how to use AnimatedNavHost to define custom enter, exit, pop enter, and pop exit transitions for composable destinations in Navigation Compose. It uses slideIntoContainer and slideOutOfContainer with specific animation specs based on the target or initial route. ```kotlin import androidx.compose.animation.AnimatedContentScope import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable import androidx.navigation.compose.composable import androidx.navigation.compose.AnimatedNavHost import androidx.navigation.compose.rememberAnimatedNavController @Composable private fun ExperimentalAnimationNav() { val navController = rememberAnimatedNavController() AnimatedNavHost(navController, startDestination = "Blue") { composable( "Blue", enterTransition = { when (initialState.destination.route) { "Red" -> slideIntoContainer(AnimatedContentScope.SlideDirection.Left, animationSpec = tween(700)) else -> null } }, exitTransition = { when (targetState.destination.route) { "Red" -> slideOutOfContainer(AnimatedContentScope.SlideDirection.Left, animationSpec = tween(700)) else -> null } }, popEnterTransition = { when (initialState.destination.route) { "Red" -> slideIntoContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(700)) else -> null } }, popExitTransition = { when (targetState.destination.route) { "Red" -> slideOutOfContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(700)) else -> null } } ) { // Composable content for Blue destination } // Other composable destinations... } } ``` -------------------------------- ### Add Accompanist Appcompat Theme Dependency Source: https://github.com/google/accompanist/blob/main/docs/appcompat-theme.md This Gradle snippet shows how to add the Accompanist Appcompat Theme library to your Android project's dependencies. It requires specifying the Maven Central repository and includes the `accompanist-appcompat-theme` artifact with a version placeholder. ```groovy repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-appcompat-theme:" } ``` -------------------------------- ### Add Accompanist Permissions Dependency (Gradle) Source: https://github.com/google/accompanist/blob/main/permissions/README.md This code snippet shows how to add the Accompanist Permissions library as a dependency to your Android project using Gradle. Ensure you replace '' with the latest stable version. This library is essential for managing runtime permissions declaratively in Jetpack Compose. ```groovy repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-permissions:" } ``` -------------------------------- ### Register a Bottom Sheet Destination in NavHost Source: https://github.com/google/accompanist/blob/main/docs/navigation-material.md Illustrates how to define a bottom sheet destination within the NavHost using the `bottomSheet` composable function. This allows navigation to a screen presented as a modal bottom sheet. ```kotlin import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.google.accompanist.navigation.material.ModalBottomSheetLayout import com.google.accompanist.navigation.material.bottomSheet import com.google.accompanist.navigation.material.rememberBottomSheetNavigator @Composable fun MyApp() { val bottomSheetNavigator = rememberBottomSheetNavigator() val navController = rememberNavController(bottomSheetNavigator) ModalBottomSheetLayout(bottomSheetNavigator) { NavHost(navController, "home") { composable(route = "home") { // Content for home screen } bottomSheet(route = "sheet") { Text("This is a cool bottom sheet!") } } } } ``` -------------------------------- ### Accompanist Navigation Material Gradle Dependency Source: https://github.com/google/accompanist/blob/main/docs/navigation-material.md Provides the Gradle dependency configuration for including the Accompanist Navigation Material library in an Android project. Ensure you replace `` with the desired library version. ```groovy repositories { mavenCentral() } dependencies { implementation "com.google.accompanist:accompanist-navigation-material:" } ``` -------------------------------- ### Compose Image with Drawable Painter (Kotlin) Source: https://github.com/google/accompanist/blob/main/docs/drawablepainter.md This snippet demonstrates how to use the `rememberDrawablePainter` function to display an Android Drawable within a Jetpack Compose `Image` composable. It requires an Android context and a Drawable resource. The output is a Composable function that renders the image. ```kotlin import androidx.appcompat.content.res.AppCompatResources import androidx.compose.foundation.Image import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import com.google.accompanist.drawablepainter.rememberDrawablePainter @Composable fun DrawDrawable() { val drawable = AppCompatResources.getDrawable(LocalContext.current, R.drawable.rectangle) Image( painter = rememberDrawablePainter(drawable = drawable), contentDescription = "content description" ) } ``` -------------------------------- ### Control Back Press Capture in WebView Source: https://github.com/google/accompanist/blob/main/docs/web.md Explains how to disable the WebView's default behavior of capturing back presses or swipes. This is controlled by the `captureBackPresses` parameter in the `WebView` Composable. ```kotlin WebView( ... captureBackPresses = false ) ``` -------------------------------- ### Define Font Family in XML Theme Source: https://github.com/google/accompanist/blob/main/docs/appcompat-theme.md This XML snippet demonstrates how to define a custom font family within an Android application's theme. It relies on the `fontFamily` attribute to reference a font resource. This is relevant for applying custom typography in Compose via theme settings. ```xml ```