### Dynamic Properties Example
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates how to dynamically change properties like color, stroke width, and opacity of a Lottie animation in Compose.
```APIDOC
## Dynamic Properties Example
### Description
This example shows how to modify animation properties such as color, stroke width, and opacity at runtime using `rememberLottieDynamicProperties` and `rememberLottieDynamicProperty`.
### Method
Composable Function
### Endpoint
N/A (Jetpack Compose Component)
### Parameters
N/A
### Request Example
```kotlin
@Composable
fun DynamicPropertiesExample() {
var starColor by remember { mutableStateOf(Color.Yellow) }
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.star_rating)
)
// Create dynamic properties
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(
property = LottieProperty.COLOR,
value = starColor.toArgb(),
keyPath = arrayOf("Star", "Fill", "Color")
),
rememberLottieDynamicProperty(
property = LottieProperty.STROKE_WIDTH,
value = 5f,
keyPath = arrayOf("Outline", "**")
),
rememberLottieDynamicProperty(
property = LottieProperty.OPACITY,
value = 80, // 0-100
keyPath = arrayOf("Background")
)
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
LottieAnimation(
composition = composition,
iterations = LottieConstants.IterateForever,
dynamicProperties = dynamicProperties,
modifier = Modifier.size(200.dp)
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
ColorButton(Color.Yellow) { starColor = it }
ColorButton(Color.Red) { starColor = it }
ColorButton(Color.Blue) { starColor = it }
}
}
}
```
### Response
N/A (Composable UI Element)
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Implement Basic Lottie Animations in Compose
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates how to load a Lottie composition from raw resources and render it using the LottieAnimation composable. Includes examples of both manual progress tracking and automatic animation handling.
```kotlin
@Composable
fun BasicLottieAnimation() {
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.RawRes(R.raw.loading)
)
val progress by animateLottieCompositionAsState(
composition = composition,
iterations = LottieConstants.IterateForever
)
LottieAnimation(
composition = composition,
progress = { progress },
modifier = Modifier.size(200.dp)
)
}
@Composable
fun SimplestUsage() {
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.heart)
)
LottieAnimation(
composition = composition,
iterations = LottieConstants.IterateForever,
modifier = Modifier.size(150.dp)
)
}
```
--------------------------------
### Load Lottie Animations from Diverse Sources
Source: https://context7.com/airbnb/lottie-android/llms.txt
Provides examples for initializing Lottie compositions from external URLs, local assets, JSON strings, file paths, and Android ContentProvider URIs.
```kotlin
@Composable
fun LoadFromUrl() {
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.Url("https://assets.lottiefiles.com/packages/lf20_example.json")
)
LottieAnimation(
composition = composition,
iterations = LottieConstants.IterateForever
)
}
@Composable
fun LoadFromAsset() {
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.Asset("animations/confetti.json")
)
LottieAnimation(
composition = composition,
iterations = 1
)
}
@Composable
fun LoadFromJsonString(jsonString: String) {
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.JsonString(jsonString)
)
LottieAnimation(
composition = composition,
modifier = Modifier.fillMaxWidth()
)
}
@Composable
fun LoadFromFile(filePath: String) {
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.File(filePath)
)
LottieAnimation(composition = composition)
}
@Composable
fun LoadFromContentProvider(uri: Uri) {
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.ContentProvider(uri)
)
LottieAnimation(composition = composition)
}
```
--------------------------------
### Configure Lottie Animation Rendering in Jetpack Compose
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates comprehensive configuration for Lottie animations in Jetpack Compose, covering rendering modes (HARDWARE, SOFTWARE), asynchronous updates, safety features, debugging outlines, layer properties (opacity, shadows, merge paths), image bounds, clipping behavior, alignment, content scaling, and custom font mapping. This example utilizes R.raw.complex_animation and custom font assets.
```kotlin
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.res.ResourcesCompat
import com.airbnb.lottie.compose.*
@Composable
fun FullConfigurationExample() {
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.RawRes(R.raw.complex_animation),
imageAssetsFolder = "images/",
fontAssetsFolder = "fonts/",
fontFileExtension = ".ttf",
cacheKey = "my_animation_v1"
)
LottieAnimation(
composition = composition,
iterations = LottieConstants.IterateForever,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f),
// Rendering options
renderMode = RenderMode.HARDWARE,
asyncUpdates = AsyncUpdates.ENABLED,
safeMode = true,
// Debugging
outlineMasksAndMattes = false, // Enable to debug performance
// Layer options
applyOpacityToLayers = false,
applyShadowToLayers = true,
enableMergePaths = true,
// Image handling
maintainOriginalImageBounds = true,
// Clipping
clipToCompositionBounds = true,
clipTextToBoundingBox = false,
// Layout
alignment = Alignment.Center,
contentScale = ContentScale.Fit,
// Custom fonts
fontMap = mapOf(
"Roboto" to ResourcesCompat.getFont(LocalContext.current, R.font.roboto)!!
)
)
}
```
--------------------------------
### Dynamic Text Example
Source: https://context7.com/airbnb/lottie-android/llms.txt
Shows how to dynamically update text elements within a Lottie animation at runtime, such as changing a greeting message based on user input.
```APIDOC
## Dynamic Text Example
### Description
This example illustrates how to dynamically update text layers within a Lottie animation. The `LottieProperty.TEXT` property is used to change the content of a specified text layer based on a state variable.
### Method
Composable Function
### Endpoint
N/A (Jetpack Compose Component)
### Parameters
N/A
### Request Example
```kotlin
@Composable
fun DynamicTextExample() {
var userName by remember { mutableStateOf("User") }
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.greeting)
)
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(
property = LottieProperty.TEXT,
value = "Hello, $userName!",
keyPath = arrayOf("Greeting")
)
)
Column {
LottieAnimation(
composition = composition,
dynamicProperties = dynamicProperties,
modifier = Modifier.size(200.dp)
)
TextField(
value = userName,
onValueChange = { userName = it },
label = { Text("Enter name") }
)
}
}
```
### Response
N/A (Composable UI Element)
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Jetpack Compose Lottie Animation ContentScale Options
Source: https://context7.com/airbnb/lottie-android/llms.txt
Illustrates different `ContentScale` options for Lottie animations in Jetpack Compose, demonstrating how `Fit`, `Crop`, and `FillBounds` affect the animation's display within its container. This example uses R.raw.animation.
```kotlin
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import com.airbnb.lottie.compose.*
@Composable
fun ContentScaleExamples() {
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.animation)
)
// Different content scale options
Row {
// Fit - Scale to fit, maintain aspect ratio
LottieAnimation(
composition = composition,
contentScale = ContentScale.Fit,
modifier = Modifier.weight(1f)
)
// Crop - Scale to fill, may clip
LottieAnimation(
composition = composition,
contentScale = ContentScale.Crop,
modifier = Modifier.weight(1f)
)
// FillBounds - Stretch to fill
LottieAnimation(
composition = composition,
contentScale = ContentScale.FillBounds,
modifier = Modifier.weight(1f)
)
}
}
```
--------------------------------
### Monitor Lottie Animation Lifecycle Events in Kotlin
Source: https://context7.com/airbnb/lottie-android/llms.txt
This snippet demonstrates how to attach an Animator.AnimatorListener to a LottieAnimationView to receive callbacks for animation start, end, cancel, and repeat events. It also shows how to clean up these listeners in onDestroy to prevent memory leaks.
```Kotlin
animationView.addAnimatorListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {
Log.d("Lottie", "Animation started")
}
override fun onAnimationEnd(animation: Animator) {
Log.d("Lottie", "Animation ended")
}
override fun onAnimationCancel(animation: Animator) {
Log.d("Lottie", "Animation cancelled")
}
override fun onAnimationRepeat(animation: Animator) {
Log.d("Lottie", "Animation repeated, iteration: ${animationView.frame}")
}
})
animationView.removeAllAnimatorListeners()
```
--------------------------------
### Track Lottie Animation Progress Updates in Kotlin
Source: https://context7.com/airbnb/lottie-android/llms.txt
This code shows how to use addAnimatorUpdateListener to get frame-by-frame progress updates of a Lottie animation. The listener receives the animation object, from which the current progress and frame can be extracted and used for UI updates, such as updating a progress bar.
```Kotlin
animationView.addAnimatorUpdateListener { animation ->
val progress = animation.animatedValue as Float
Log.d("Lottie", "Progress: $progress, Frame: ${animationView.frame}")
// Update UI based on animation progress
progressBar.progress = (progress * 100).toInt()
}
animationView.removeAllUpdateListeners()
```
--------------------------------
### Manage and Replace Image Assets in Lottie
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates how to configure image asset folders, replace bitmaps at runtime, and implement custom image loading logic using ImageAssetDelegate. This is essential for animations that require dynamic content or network-fetched images.
```kotlin
class ImageAssetsExample : AppCompatActivity() {
private lateinit var animationView: LottieAnimationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
animationView = findViewById(R.id.animation_view)
animationView.setImageAssetsFolder("images/")
animationView.setAnimation("animation_with_images.json")
animationView.playAnimation()
}
fun replaceImage(newBitmap: Bitmap) {
animationView.updateBitmap("image_0", newBitmap)
}
fun setupCustomImageLoading() {
animationView.setImageAssetDelegate { asset ->
val bitmap = loadBitmapFromNetwork(asset.fileName)
bitmap
}
}
fun setupWithOriginalBounds() {
animationView.setMaintainOriginalImageBounds(true)
}
}
```
--------------------------------
### Load Lottie Animation from Raw Resources (LottieAnimationView)
Source: https://context7.com/airbnb/lottie-android/llms.txt
Shows how to load a Lottie animation from the `res/raw` directory using `LottieAnimationView`. This method offers compile-time type safety. It also demonstrates controlling playback using frame ranges, progress values, and markers defined in After Effects.
```kotlin
class AnimationActivity : AppCompatActivity() {
private lateinit var animationView: LottieAnimationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_animation)
animationView = findViewById(R.id.animation_view)
// Load from res/raw/confetti.json
animationView.setAnimation(R.raw.confetti)
// Play only a portion of the animation using frames
animationView.setMinAndMaxFrame(0, 60)
// Or using progress (0f to 1f)
animationView.setMinAndMaxProgress(0.2f, 0.8f)
// Or using markers defined in After Effects
animationView.setMinAndMaxFrame("Intro", "Loop", true)
animationView.playAnimation()
}
}
```
```xml
```
--------------------------------
### Initialize Lottie with Global Configuration
Source: https://context7.com/airbnb/lottie-android/llms.txt
Configures Lottie globally by overriding default settings such as network fetcher, cache directory, and performance options. This is typically done in the Application class's onCreate method.
```kotlin
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Lottie.initialize(
LottieConfig.Builder()
// Custom network stack
.setNetworkFetcher(OkHttpNetworkFetcher())
// Custom network cache
.setNetworkCacheDir(File(cacheDir, "lottie_network"))
// Disable network cache entirely
.setDisablePathInterpolatorCache(false)
// Enable systrace markers for debugging
.setEnableSystraceMarkers(true)
// Default async updates setting
.setDefaultAsyncUpdates(AsyncUpdates.ENABLED)
// Reduced motion settings
.setReducedMotionOption(ReducedMotionOption.SYSTEM)
.build()
)
}
}
```
--------------------------------
### Execute Release Build and Upload
Source: https://github.com/airbnb/lottie-android/blob/master/RELEASE.md
This command triggers a clean build and uploads the library archives to the configured repository. It is a critical step in the release pipeline that requires proper authentication and repository configuration.
```bash
./gradlew clean uploadArchives
```
--------------------------------
### Configure Lottie Render Modes and Performance Tracking
Source: https://context7.com/airbnb/lottie-android/llms.txt
Explains how to optimize LottieAnimationView performance by switching between hardware and software rendering, enabling async updates, and accessing performance metrics.
```kotlin
class RenderModeExample : AppCompatActivity() {
private lateinit var animationView: LottieAnimationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
animationView = findViewById(R.id.animation_view)
animationView.setRenderMode(RenderMode.AUTOMATIC)
animationView.setRenderMode(RenderMode.HARDWARE)
animationView.setRenderMode(RenderMode.SOFTWARE)
animationView.setAsyncUpdates(AsyncUpdates.ENABLED)
animationView.setSafeMode(true)
animationView.setPerformanceTrackingEnabled(true)
animationView.setAnimation(R.raw.complex_animation)
animationView.playAnimation()
Handler(Looper.getMainLooper()).postDelayed({
animationView.performanceTracker?.let { tracker ->
Log.d("Lottie", "Render times: ${tracker.renderTimes}")
}
}, 5000)
}
}
```
```xml
```
--------------------------------
### Programmatic Animation Loading with LottieCompositionFactory
Source: https://context7.com/airbnb/lottie-android/llms.txt
Provides advanced control over animation loading using LottieCompositionFactory. Covers asynchronous and synchronous loading from assets, raw resources, JSON strings, input streams, and zip files, as well as cache management.
```kotlin
class CompositionFactoryExample {
fun loadFromAssetAsync(context: Context) {
LottieCompositionFactory.fromAsset(context, "animations/heart.json")
.addListener { composition ->
Log.d("Lottie", "Frames: ${composition.startFrame} - ${composition.endFrame}")
}
.addFailureListener { exception ->
Log.e("Lottie", "Failed to load", exception)
}
}
fun loadFromRawResSync(context: Context): LottieComposition? {
val result = LottieCompositionFactory.fromRawResSync(context, R.raw.animation)
return result.value
}
fun loadFromJsonString(context: Context, jsonString: String) {
LottieCompositionFactory.fromJsonString(context, jsonString, "cache_key")
.addListener { composition -> }
}
fun loadFromInputStream(context: Context, inputStream: InputStream) {
LottieCompositionFactory.fromInputStream(context, inputStream, "unique_cache_key")
.addListener { composition -> }
}
fun loadFromZipWithImages(context: Context) {
val zipStream = ZipInputStream(context.assets.open("animation_with_images.zip"))
LottieCompositionFactory.fromZipStream(context, zipStream, "zip_animation")
.addListener { composition -> }
}
fun preloadAndCache(context: Context, url: String) {
LottieCompositionFactory.fromUrl(context, url, "preload_$url")
}
fun clearCache(context: Context) {
LottieCompositionFactory.clearCache(context)
}
}
```
--------------------------------
### Manual Bitmap Asset Injection
Source: https://github.com/airbnb/lottie-android/blob/master/CHANGELOG_COMPOSE.md
Demonstrates how to manually supply bitmaps to a Lottie composition to avoid IO operations on the main thread. This replaces the previous callback-based image loading approach.
```kotlin
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.animation))
composition.images["your_image_id"]?.bitmap = yourBitmap
```
--------------------------------
### Load Lottie Animations from Network URL
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates how to load animations directly from a URL using LottieAnimationView in Kotlin and XML. It includes handling for fallback resources, error listeners, and composition loading callbacks.
```kotlin
class NetworkAnimationActivity : AppCompatActivity() {
private lateinit var animationView: LottieAnimationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_network)
animationView = findViewById(R.id.animation_view)
animationView.setAnimationFromUrl("https://assets.lottiefiles.com/packages/lf20_example.json")
animationView.setFallbackResource(R.drawable.error_placeholder)
animationView.setFailureListener { exception ->
Log.e("Lottie", "Failed to load animation", exception)
}
animationView.addLottieOnCompositionLoadedListener { composition ->
Log.d("Lottie", "Animation loaded: ${composition.duration}ms duration")
animationView.playAnimation()
}
}
}
```
```xml
```
--------------------------------
### Manage Lottie Loading and Error States in Compose
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates how to use rememberLottieComposition to observe loading, error, and success states. It displays a progress indicator while loading, an error message upon failure, and the animation once ready.
```kotlin
@Composable
fun LoadingStateExample() {
val compositionResult = rememberLottieComposition(
spec = LottieCompositionSpec.Url("https://example.com/animation.json")
)
val composition = compositionResult.value
val isLoading = compositionResult.isLoading
val error = compositionResult.error
Box(modifier = Modifier.size(200.dp), contentAlignment = Alignment.Center) {
when {
isLoading -> CircularProgressIndicator()
error != null -> Text(text = "Error: ${error.message}", color = Color.Red)
composition != null -> LottieAnimation(composition = composition, iterations = LottieConstants.IterateForever)
}
}
}
```
--------------------------------
### Basic Lottie Animation with LottieAnimationView (Asset)
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates how to load and play a Lottie animation from the assets folder using LottieAnimationView in an Android Activity. It includes configuration for repeat count, mode, speed, and programmatic playback control.
```kotlin
// In your Activity or Fragment
class MainActivity : AppCompatActivity() {
private lateinit var animationView: LottieAnimationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
animationView = findViewById(R.id.animation_view)
// Load from assets folder (src/main/assets/animations/loading.json)
animationView.setAnimation("animations/loading.json")
// Configure playback
animationView.repeatCount = LottieDrawable.INFINITE
animationView.repeatMode = LottieDrawable.RESTART
animationView.speed = 1.5f
// Start the animation
animationView.playAnimation()
}
override fun onPause() {
super.onPause()
animationView.pauseAnimation()
}
override fun onResume() {
super.onResume()
if (!animationView.isAnimating) {
animationView.resumeAnimation()
}
}
}
```
```xml
```
--------------------------------
### Configure Custom Fonts for Lottie Animations
Source: https://context7.com/airbnb/lottie-android/llms.txt
Shows three methods for handling custom fonts: auto-loading from assets, using a font map for explicit mapping, and implementing FontAssetDelegate for programmatic font resolution.
```kotlin
class FontsExample : AppCompatActivity() {
private lateinit var animationView: LottieAnimationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
animationView = findViewById(R.id.animation_view)
animationView.setDefaultFontFileExtension(".ttf")
val fontMap = mapOf(
"Roboto" to ResourcesCompat.getFont(this, R.font.roboto_regular)!!,
"Roboto-Bold" to ResourcesCompat.getFont(this, R.font.roboto_bold)!!,
"CustomFont" to Typeface.createFromAsset(assets, "fonts/custom.otf")
)
animationView.setFontMap(fontMap)
animationView.setFontAssetDelegate(object : FontAssetDelegate() {
override fun fetchFont(fontFamily: String, fontStyle: String, fontName: String): Typeface? {
return when (fontFamily) {
"Roboto" -> ResourcesCompat.getFont(this@FontsExample, R.font.roboto_regular)
else -> null
}
}
override fun getFontPath(fontFamily: String, fontStyle: String, fontName: String): String? {
return "fonts/$fontFamily.ttf"
}
})
animationView.setAnimation(R.raw.text_animation)
animationView.playAnimation()
}
}
```
--------------------------------
### Await Lottie Composition Loading
Source: https://context7.com/airbnb/lottie-android/llms.txt
Utilizes LaunchedEffect and the await() function to handle Lottie composition loading asynchronously. This approach is useful for performing side effects or logging once the animation resource is fully loaded.
```kotlin
@Composable
fun AwaitCompositionExample() {
val compositionResult = rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.animation))
LaunchedEffect(compositionResult) {
try {
val composition = compositionResult.await()
Log.d("Lottie", "Duration: ${composition.duration}ms")
} catch (e: Exception) {
Log.e("Lottie", "Failed to load", e)
}
}
LottieAnimation(composition = compositionResult.value, iterations = LottieConstants.IterateForever)
}
```
--------------------------------
### Implement Dynamic Text Replacement
Source: https://context7.com/airbnb/lottie-android/llms.txt
Explains how to use TextDelegate to replace static text layers within a Lottie animation with dynamic data at runtime.
```kotlin
class TextDelegateExample : AppCompatActivity() {
private lateinit var animationView: LottieAnimationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
animationView = findViewById(R.id.animation_view)
val textDelegate = TextDelegate(animationView)
textDelegate.setText("Username", "John Doe")
textDelegate.setText("Score", "1,234 pts")
textDelegate.setText("Date", SimpleDateFormat("MMM dd").format(Date()))
animationView.setTextDelegate(textDelegate)
animationView.setAnimation(R.raw.profile_animation)
animationView.playAnimation()
}
fun updateScore(newScore: Int) {
(animationView.textDelegate as? TextDelegate)?.let {
it.setText("Score", NumberFormat.getInstance().format(newScore))
}
}
}
```
--------------------------------
### Implement LottieDrawable for Custom Views and Notifications
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates how to instantiate LottieDrawable manually to display animations in non-Lottie views or convert frames to bitmaps for notifications. It requires handling composition loading and manual animation lifecycle management.
```kotlin
class LottieDrawableExample : AppCompatActivity() {
private lateinit var lottieDrawable: LottieDrawable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lottieDrawable = LottieDrawable()
LottieCompositionFactory.fromRawRes(this, R.raw.loading)
.addListener { composition ->
lottieDrawable.composition = composition
lottieDrawable.repeatCount = LottieDrawable.INFINITE
lottieDrawable.playAnimation()
val imageView: ImageView = findViewById(R.id.image_view)
imageView.setImageDrawable(lottieDrawable)
val view: View = findViewById(R.id.container)
view.background = lottieDrawable
}
}
fun useInNotification(): Notification {
val drawable = LottieDrawable()
val result = LottieCompositionFactory.fromRawResSync(this, R.raw.notification_icon)
result.value?.let { composition ->
drawable.composition = composition
drawable.progress = 0.5f
}
val bitmap = Bitmap.createBitmap(48, 48, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, 48, 48)
drawable.draw(canvas)
return NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.ic_notification)
.setLargeIcon(bitmap)
.setContentTitle("Title")
.build()
}
override fun onDestroy() {
super.onDestroy()
lottieDrawable.cancelAnimation()
}
}
```
--------------------------------
### Implement Retry Logic for Lottie Animations
Source: https://context7.com/airbnb/lottie-android/llms.txt
Shows how to implement a retry mechanism with exponential backoff using the onRetry callback. It provides a UI button to manually trigger a retry if the initial load fails.
```kotlin
@Composable
fun RetryOnErrorExample() {
val retrySignal = rememberLottieRetrySignal()
val compositionResult = rememberLottieComposition(
spec = LottieCompositionSpec.Url("https://example.com/animation.json"),
onRetry = { failCount, exception ->
if (failCount < 3) {
delay(1000L * failCount)
true
} else false
}
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
if (compositionResult.isFailure) {
Text("Failed to load animation")
Button(onClick = { retrySignal.retry() }) { Text("Retry") }
} else {
LottieAnimation(composition = compositionResult.value, iterations = LottieConstants.IterateForever)
}
}
}
```
--------------------------------
### Custom OkHttp Network Fetcher for Lottie
Source: https://context7.com/airbnb/lottie-android/llms.txt
Implements a custom network fetcher for Lottie using OkHttp. This allows for custom request interception, such as adding authorization headers, and provides a synchronous fetching mechanism for Lottie animations from network URLs.
```kotlin
// Custom network fetcher with OkHttp
class OkHttpNetworkFetcher : LottieNetworkFetcher {
private val client = OkHttpClient.Builder()
.addInterceptor { chain ->
chain.proceed(
chain.request().newBuilder()
.addHeader("Authorization", "Bearer token")
.build()
)
}
.build()
override fun fetchSync(context: Context, url: String, cacheKey: String?): LottieFetchResult {
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()
return object : LottieFetchResult {
override fun close() = response.close()
override fun contentType() = response.header("Content-Type")
override fun inputStream() = response.body?.byteStream()
override fun isSuccessful() = response.isSuccessful
}
}
}
```
--------------------------------
### Initialize CompositionLayer
Source: https://github.com/airbnb/lottie-android/blob/master/lottie/src/main/generated/baselineProfiles/baseline-prof.txt
The CompositionLayer class manages a collection of sub-layers within a Lottie animation. It provides methods to set clipping bounds and update the animation progress for all child layers.
```Java
public class CompositionLayer extends BaseLayer {
public CompositionLayer(LottieDrawable lottieDrawable, Layer layerModel, List layers, LottieComposition composition) {
super(lottieDrawable, layerModel);
}
public void setClipToCompositionBounds(boolean clip) {
// Implementation to toggle clipping
}
public void setProgress(float progress) {
// Implementation to update animation progress
}
}
```
--------------------------------
### Jetpack Compose Playback Control
Source: https://context7.com/airbnb/lottie-android/llms.txt
Demonstrates controlling animation playback state (play/pause, speed) and displaying animation progress in Jetpack Compose. It uses `rememberLottieComposition` to load the animation and `animateLottieCompositionAsState` to manage playback. Dependencies include Jetpack Compose UI elements and Lottie animation specs.
```kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.airbnb.lottie.compose.*
@Composable
fun PlaybackControlExample() {
var isPlaying by remember { mutableStateOf(true) }
var speed by remember { mutableFloatStateOf(1f) }
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.animation)
)
val progress by animateLottieCompositionAsState(
composition = composition,
isPlaying = isPlaying,
speed = speed,
iterations = LottieConstants.IterateForever,
restartOnPlay = true, // Restart from beginning when playing again
reverseOnRepeat = false // Don't reverse direction on each repeat
)
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
LottieAnimation(
composition = composition,
progress = { progress },
modifier = Modifier.size(200.dp)
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = { isPlaying = !isPlaying }) {
Text(if (isPlaying) "Pause" else "Play")
}
Button(onClick = { speed = if (speed == 1f) 2f else 1f }) {
Text("Speed: ${speed}x")
}
}
Text("Progress: ${(progress * 100).toInt()}%")
}
}
@Composable
fun ClipAnimationExample() {
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.long_animation)
)
// Play only a portion of the animation
val progress by animateLottieCompositionAsState(
composition = composition,
clipSpec = LottieClipSpec.Progress(0.2f, 0.8f), // Play 20% to 80%
iterations = LottieConstants.IterateForever
)
// Or clip by frames
val progressByFrame by animateLottieCompositionAsState(
composition = composition,
clipSpec = LottieClipSpec.Frame(10, 50), // Play frames 10-50
iterations = 3
)
LottieAnimation(
composition = composition,
progress = { progress }
)
}
@Composable
fun ManualProgressControl() {
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.slider)
)
var sliderPosition by remember { mutableFloatStateOf(0f) }
Column {
LottieAnimation(
composition = composition,
progress = { sliderPosition }, // Controlled by slider
modifier = Modifier.size(200.dp)
)
Slider(
value = sliderPosition,
onValueChange = { sliderPosition = it },
modifier = Modifier.padding(16.dp)
)
}
}
```
--------------------------------
### Add Lottie-Compose Dependency to Gradle
Source: https://github.com/airbnb/lottie-android/blob/master/README.md
This snippet demonstrates how to include the Lottie-Compose library in your Android project's build.gradle file. This is for projects utilizing Jetpack Compose for UI development.
```groovy
dependencies {
implementation 'com.airbnb.android:lottie-compose:$lottieVersion'
}
```
--------------------------------
### Manage Version Control Tags
Source: https://github.com/airbnb/lottie-android/blob/master/RELEASE.md
Creates an annotated Git tag for the specific release version. This ensures that the repository history reflects the exact state of the codebase at the time of release.
```bash
git tag -a X.Y.Z -m "Version X.Y.Z"
```
--------------------------------
### animateLottieCompositionAsState
Source: https://context7.com/airbnb/lottie-android/llms.txt
Configures the playback state of a Lottie animation including play/pause, speed, and iteration settings.
```APIDOC
## animateLottieCompositionAsState
### Description
Controls the animation playback state, speed, and repetition logic within a Compose component.
### Parameters
- **composition** (LottieComposition) - Required - The loaded Lottie composition.
- **isPlaying** (Boolean) - Optional - Whether the animation is currently playing.
- **speed** (Float) - Optional - Playback speed multiplier.
- **iterations** (Int) - Optional - Number of times to repeat.
- **restartOnPlay** (Boolean) - Optional - Whether to reset to start on play.
### Request Example
val progress by animateLottieCompositionAsState(
composition = composition,
isPlaying = isPlaying,
speed = speed,
iterations = LottieConstants.IterateForever
)
```
--------------------------------
### Jetpack Compose: Dynamic Lottie Animation Properties
Source: https://context7.com/airbnb/lottie-android/llms.txt
This snippet shows how to dynamically adjust properties of a Lottie animation in Jetpack Compose. It demonstrates changing color, stroke width, and opacity based on state or predefined values. Dependencies include Jetpack Compose UI, Lottie Compose library, and Android graphics color utilities.
```kotlin
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.TextField
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.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.unit.dp
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.LottieProperty
import com.airbnb.lottie.compose.ScaleXY
import com.airbnb.lottie.compose.rememberLottieComposition
import com.airbnb.lottie.compose.rememberLottieDynamicProperties
import com.airbnb.lottie.compose.rememberLottieDynamicProperty
import kotlin.math.sin
@Composable
fun DynamicPropertiesExample() {
var starColor by remember { mutableStateOf(Color.Yellow) }
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.star_rating)
)
// Create dynamic properties
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(
property = LottieProperty.COLOR,
value = starColor.toArgb(),
keyPath = arrayOf("Star", "Fill", "Color")
),
rememberLottieDynamicProperty(
property = LottieProperty.STROKE_WIDTH,
value = 5f,
keyPath = arrayOf("Outline", "**")
),
rememberLottieDynamicProperty(
property = LottieProperty.OPACITY,
value = 80, // 0-100
keyPath = arrayOf("Background")
)
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
LottieAnimation(
composition = composition,
iterations = LottieConstants.IterateForever,
dynamicProperties = dynamicProperties,
modifier = Modifier.size(200.dp)
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
ColorButton(Color.Yellow) { starColor = it }
ColorButton(Color.Red) { starColor = it }
ColorButton(Color.Blue) { starColor = it }
}
}
}
@Composable
fun DynamicPropertyWithCallback() {
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.animated_shape)
)
// Use callback for frame-dependent values
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(
property = LottieProperty.TRANSFORM_SCALE,
keyPath = arrayOf("Icon")
) { frameInfo ->
// Pulse effect based on animation progress
val scale = 1f + 0.2f * sin(frameInfo.overallProgress * Math.PI * 4).toFloat()
ScaleXY(scale, scale)
},
rememberLottieDynamicProperty(
property = LottieProperty.COLOR,
keyPath = arrayOf("Background", "Fill")
) { frameInfo ->
// Color changes over time
val hue = (frameInfo.overallProgress * 360).toInt()
android.graphics.Color.HSVToColor(floatArrayOf(hue.toFloat(), 0.8f, 1f))
}
)
LottieAnimation(
composition = composition,
iterations = LottieConstants.IterateForever,
dynamicProperties = dynamicProperties
)
}
@Composable
fun DynamicTextExample() {
var userName by remember { mutableStateOf("User") }
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(R.raw.greeting)
)
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(
property = LottieProperty.TEXT,
value = "Hello, $userName!",
keyPath = arrayOf("Greeting")
)
)
Column {
LottieAnimation(
composition = composition,
dynamicProperties = dynamicProperties,
modifier = Modifier.size(200.dp)
)
TextField(
value = userName,
onValueChange = { userName = it },
label = { Text("Enter name") }
)
}
}
// Dummy composables for compilation, replace with actual implementations
@Composable
fun ColorButton(color: Color, onClick: (Color) -> Unit) {
Button(onClick = { onClick(color) })
}
@Composable
fun Text(text: String) {
// Placeholder for Text composable
}
@Composable
fun TextField(value: String, onValueChange: (String) -> Unit, label: @Composable () -> Unit) {
// Placeholder for TextField composable
}
// Dummy R.raw object for compilation
object R {
object raw {
val star_rating = 0
val animated_shape = 1
val greeting = 2
}
}
```
--------------------------------
### Push Changes and Tags to Remote
Source: https://github.com/airbnb/lottie-android/blob/master/RELEASE.md
Synchronizes the local commits and tags with the remote repository. This makes the new version and release history publicly available.
```bash
git push && git push --tags
```
--------------------------------
### Content Model Parser
Source: https://github.com/airbnb/lottie-android/blob/master/lottie/src/main/generated/baselineProfiles/baseline-prof.txt
Parser for general content models in Lottie animations.
```APIDOC
## Content Model Parser
### Description
Parses various content models used in Lottie animations.
### Method
- `parse(JsonReader reader, LottieComposition composition)`
- **Description**: Parses a generic `ContentModel` from the JSON reader.
- **Returns**: `ContentModel` object.
```
--------------------------------
### Lottie Properties
Source: https://context7.com/airbnb/lottie-android/llms.txt
This section details the available properties for dynamic value callbacks in Lottie animations, categorized for clarity.
```APIDOC
## Lottie Property Reference
Available properties for dynamic value callbacks.
### Transform Properties
- **LottieProperty.TRANSFORM_ANCHOR_POINT** (PointF) - Anchor point in pixels
- **LottieProperty.TRANSFORM_POSITION** (PointF) - Position in pixels
- **LottieProperty.TRANSFORM_POSITION_X** (Float) - X position when split dimensions enabled
- **LottieProperty.TRANSFORM_POSITION_Y** (Float) - Y position when split dimensions enabled
- **LottieProperty.TRANSFORM_SCALE** (ScaleXY) - Scale factor
- **LottieProperty.TRANSFORM_ROTATION** (Float) - Rotation in degrees
- **LottieProperty.TRANSFORM_ROTATION_X** (Float) - 3D X rotation in degrees
- **LottieProperty.TRANSFORM_ROTATION_Y** (Float) - 3D Y rotation in degrees
- **LottieProperty.TRANSFORM_ROTATION_Z** (Float) - 3D Z rotation in degrees
- **LottieProperty.TRANSFORM_OPACITY** (Integer) - Opacity 0-100
- **LottieProperty.TRANSFORM_SKEW** (Float) - Skew 0-85
- **LottieProperty.TRANSFORM_SKEW_ANGLE** (Float) - Skew angle in degrees
- **LottieProperty.TRANSFORM_START_OPACITY** (Float) - Repeater start opacity 0-100
- **LottieProperty.TRANSFORM_END_OPACITY** (Float) - Repeater end opacity 0-100
### Fill/Stroke Properties
- **LottieProperty.COLOR** (Integer) - ColorInt (ARGB)
- **LottieProperty.STROKE_COLOR** (Integer) - ColorInt (ARGB)
- **LottieProperty.OPACITY** (Integer) - Opacity 0-100
- **LottieProperty.STROKE_WIDTH** (Float) - Width in pixels
- **LottieProperty.COLOR_FILTER** (ColorFilter)
- **LottieProperty.GRADIENT_COLOR** (Integer[]) - Array of ARGB colors
### Shape Properties
- **LottieProperty.POSITION** (PointF) - Shape position in pixels
- **LottieProperty.ELLIPSE_SIZE** (PointF) - Ellipse size in pixels
- **LottieProperty.RECTANGLE_SIZE** (PointF) - Rectangle size in pixels
- **LottieProperty.CORNER_RADIUS** (Float) - Corner radius in degrees
- **LottieProperty.PATH** (Path) - Replace entire path
### Polystar Properties
- **LottieProperty.POLYSTAR_POINTS** (Float) - Number of points
- **LottieProperty.POLYSTAR_ROTATION** (Float) - Rotation in degrees
- **LottieProperty.POLYSTAR_INNER_RADIUS** (Float) - Inner radius in pixels (star)
- **LottieProperty.POLYSTAR_OUTER_RADIUS** (Float) - Outer radius in pixels
- **LottieProperty.POLYSTAR_INNER_ROUNDEDNESS** (Float) - Inner roundedness 0-100 (star)
- **LottieProperty.POLYSTAR_OUTER_ROUNDEDNESS** (Float) - Outer roundedness 0-100
### Repeater Properties
- **LottieProperty.REPEATER_COPIES** (Float) - Number of copies
- **LottieProperty.REPEATER_OFFSET** (Float) - Offset amount
### Text Properties
- **LottieProperty.TEXT** (CharSequence) - Text content
- **LottieProperty.TEXT_SIZE** (Float) - Text size in dp
- **LottieProperty.TEXT_TRACKING** (Float) - Character spacing
- **LottieProperty.TYPEFACE** (Typeface) - Font face
### Image Properties
- **LottieProperty.IMAGE** (Bitmap) - Replace image
### Effect Properties
- **LottieProperty.BLUR_RADIUS** (Float) - Blur radius in pixels
- **LottieProperty.DROP_SHADOW_COLOR** (Integer) - ColorInt (ARGB)
- **LottieProperty.DROP_SHADOW_OPACITY** (Float) - 0-100
- **LottieProperty.DROP_SHADOW_DIRECTION** (Float) - Direction in degrees
- **LottieProperty.DROP_SHADOW_DISTANCE** (Float) - Distance in pixels
- **LottieProperty.DROP_SHADOW_RADIUS** (Float) - Blur radius in pixels
### Time Properties
- **LottieProperty.TIME_REMAP** (Float) - Time value in seconds
```
--------------------------------
### Add Lottie Dependency to Gradle
Source: https://github.com/airbnb/lottie-android/blob/master/README.md
This snippet shows how to add the Lottie library dependency to your Android project's build.gradle file using Gradle. It specifies the implementation dependency for the Lottie library.
```groovy
dependencies {
implementation 'com.airbnb.android:lottie:$lottieVersion'
}
```
--------------------------------
### Migrate LottieAnimation Progress API
Source: https://github.com/airbnb/lottie-android/blob/master/CHANGELOG_COMPOSE.md
Updates the LottieAnimation component to use a lambda for progress tracking. This change optimizes performance by avoiding recomposition on every progress update.
```kotlin
LottieAnimation(composition, { progress })
```
```kotlin
LottieAnimation(
composition = composition,
progress = { progress }
)
```