0
# Composition Loading
1
2
Factory methods and async operations for loading Lottie animations from various sources including assets, raw resources, URLs, and streams. All loading operations return `LottieTask` instances for async handling with built-in caching support.
3
4
## Capabilities
5
6
### LottieCompositionFactory
7
8
Factory class providing static methods for loading animations from different sources. All methods return `LottieTask<LottieComposition>` for async handling.
9
10
```java { .api }
11
/**
12
* Factory for creating LottieComposition instances from various sources
13
*/
14
public class LottieCompositionFactory {
15
// Asset loading
16
public static LottieTask<LottieComposition> fromAsset(Context context, String fileName);
17
public static LottieTask<LottieComposition> fromAsset(Context context, String fileName, String cacheKey);
18
19
// Raw resource loading
20
public static LottieTask<LottieComposition> fromRawRes(Context context, @RawRes int rawRes);
21
public static LottieTask<LottieComposition> fromRawRes(Context context, @RawRes int rawRes, String cacheKey);
22
23
// URL loading with caching
24
public static LottieTask<LottieComposition> fromUrl(Context context, String url);
25
public static LottieTask<LottieComposition> fromUrl(Context context, String url, String cacheKey);
26
27
// JSON string loading
28
public static LottieTask<LottieComposition> fromJsonString(String json, String cacheKey);
29
public static LottieTask<LottieComposition> fromJsonInputStream(InputStream stream, String cacheKey);
30
public static LottieTask<LottieComposition> fromJsonReader(JsonReader reader, String cacheKey);
31
public static LottieTask<LottieComposition> fromJson(JSONObject json, String cacheKey);
32
33
// ZIP file loading (for animations with images)
34
public static LottieTask<LottieComposition> fromZipStream(ZipInputStream inputStream, String cacheKey);
35
public static LottieTask<LottieComposition> fromZipStreamSync(ZipInputStream inputStream, String cacheKey);
36
37
// Synchronous loading methods (use with caution on main thread)
38
public static LottieResult<LottieComposition> fromAssetSync(Context context, String fileName);
39
public static LottieResult<LottieComposition> fromAssetSync(Context context, String fileName, String cacheKey);
40
public static LottieResult<LottieComposition> fromRawResSync(Context context, @RawRes int rawRes);
41
public static LottieResult<LottieComposition> fromRawResSync(Context context, @RawRes int rawRes, String cacheKey);
42
public static LottieResult<LottieComposition> fromUrlSync(Context context, String url);
43
public static LottieResult<LottieComposition> fromUrlSync(Context context, String url, String cacheKey);
44
public static LottieResult<LottieComposition> fromJsonStringSync(String json, String cacheKey);
45
public static LottieResult<LottieComposition> fromJsonInputStreamSync(InputStream stream, String cacheKey);
46
public static LottieResult<LottieComposition> fromJsonSync(JSONObject json, String cacheKey);
47
public static LottieResult<LottieComposition> fromJsonReaderSync(JsonReader reader, String cacheKey);
48
49
// Cache management
50
public static void setMaxCacheSize(int size);
51
public static void clearCache(Context context);
52
}
53
```
54
55
**Usage Examples:**
56
57
```java
58
// Load from assets
59
LottieCompositionFactory.fromAsset(context, "animation.json")
60
.addListener(composition -> {
61
animationView.setComposition(composition);
62
animationView.playAnimation();
63
})
64
.addFailureListener(throwable -> {
65
Log.e("Lottie", "Failed to load animation", throwable);
66
});
67
68
// Load from raw resources
69
LottieCompositionFactory.fromRawRes(context, R.raw.loading_animation)
70
.addListener(animationView::setComposition);
71
72
// Load from URL with custom cache key
73
LottieCompositionFactory.fromUrl(context, "https://example.com/animation.json", "custom_key")
74
.addListener(composition -> {
75
drawable.setComposition(composition);
76
drawable.playAnimation();
77
});
78
79
// Load from JSON string
80
String animationJson = "{ ... }"; // Lottie JSON
81
LottieCompositionFactory.fromJsonString(animationJson, "inline_animation")
82
.addListener(composition -> {
83
// Use composition
84
});
85
86
// Load from input stream
87
try (InputStream stream = new FileInputStream(animationFile)) {
88
LottieCompositionFactory.fromJsonInputStream(stream, "file_animation")
89
.addListener(composition -> {
90
// Use composition
91
});
92
}
93
94
// Load ZIP file (with images)
95
try (ZipInputStream zipStream = new ZipInputStream(new FileInputStream(zipFile))) {
96
LottieCompositionFactory.fromZipStream(zipStream, "zip_animation")
97
.addListener(composition -> {
98
// Use composition
99
});
100
}
101
102
// Synchronous loading (background thread only)
103
ExecutorService executor = Executors.newSingleThreadExecutor();
104
executor.execute(() -> {
105
LottieResult<LottieComposition> result =
106
LottieCompositionFactory.fromAssetSync(context, "animation.json");
107
108
if (result.getValue() != null) {
109
// Success - switch to main thread to use composition
110
Handler mainHandler = new Handler(Looper.getMainLooper());
111
mainHandler.post(() -> {
112
animationView.setComposition(result.getValue());
113
});
114
} else {
115
Log.e("Lottie", "Failed to load", result.getException());
116
}
117
});
118
119
// Cache management
120
LottieCompositionFactory.setMaxCacheSize(50); // Increase cache size
121
LottieCompositionFactory.clearCache(context); // Clear all cached animations
122
```
123
124
### LottieComposition
125
126
Immutable composition model representing a parsed After Effects animation. Contains all animation data including layers, assets, timing information, and metadata.
127
128
```java { .api }
129
/**
130
* Immutable composition model representing parsed After Effects animation
131
*/
132
public class LottieComposition {
133
// Bounds and dimensions
134
public Rect getBounds();
135
136
// Timing information
137
public float getDuration(); // Duration in milliseconds
138
public float getDurationAsSeconds(); // Duration in seconds
139
public float getStartFrame();
140
public float getEndFrame();
141
public float getFrameRate();
142
public float getDurationFrames(); // Duration in frames
143
144
// Animation structure
145
public List<Layer> getLayers();
146
public LongSparseArray<Layer> getLayerMap();
147
public Map<String, List<Layer>> getPrecomps();
148
149
// Assets
150
public Map<String, LottieImageAsset> getImages();
151
public boolean hasImages();
152
public Map<String, Font> getFonts();
153
public SparseArrayCompat<FontCharacter> getCharacters();
154
155
// Markers
156
public List<Marker> getMarkers();
157
public Marker getMarker(String markerName);
158
159
// Performance characteristics
160
public boolean hasDashPattern();
161
public int getMaskAndMatteCount();
162
163
// Debugging and analysis
164
public Set<String> getWarnings();
165
public PerformanceTracker getPerformanceTracker();
166
167
// Internal methods (library use)
168
@RestrictTo(RestrictTo.Scope.LIBRARY)
169
public void addWarning(String warning);
170
@RestrictTo(RestrictTo.Scope.LIBRARY)
171
public void setHasDashPattern(boolean hasDashPattern);
172
@RestrictTo(RestrictTo.Scope.LIBRARY)
173
public void incrementMatteOrMaskCount(int amount);
174
}
175
```
176
177
**Usage Examples:**
178
179
```java
180
// Analyze composition
181
LottieCompositionFactory.fromAsset(context, "complex_animation.json")
182
.addListener(composition -> {
183
Log.d("Lottie", "Duration: " + composition.getDurationAsSeconds() + "s");
184
Log.d("Lottie", "Frame rate: " + composition.getFrameRate() + " fps");
185
Log.d("Lottie", "Has images: " + composition.hasImages());
186
Log.d("Lottie", "Mask/matte count: " + composition.getMaskAndMatteCount());
187
188
// Check for markers
189
List<Marker> markers = composition.getMarkers();
190
for (Marker marker : markers) {
191
Log.d("Lottie", "Marker: " + marker.getName() +
192
" at frame " + marker.getStartFrame());
193
}
194
195
// Check warnings
196
Set<String> warnings = composition.getWarnings();
197
if (!warnings.isEmpty()) {
198
Log.w("Lottie", "Animation warnings: " + warnings);
199
}
200
});
201
202
// Use composition bounds for layout
203
composition.getBounds(); // Returns Rect with animation bounds
204
int width = composition.getBounds().width();
205
int height = composition.getBounds().height();
206
207
// Performance analysis
208
PerformanceTracker tracker = composition.getPerformanceTracker();
209
tracker.setEnabled(true);
210
// ... after animation plays
211
Map<String, Float> renderTimes = tracker.getSortedRenderTimes();
212
```
213
214
### LottieTask
215
216
Async task wrapper for handling loading operations with success and failure callbacks. Provides chainable API for handling results.
217
218
```java { .api }
219
/**
220
* Async task helper for loading operations
221
*/
222
public class LottieTask<T> {
223
// Result listeners
224
public LottieTask<T> addListener(LottieListener<T> listener);
225
public LottieTask<T> removeListener(LottieListener<T> listener);
226
public LottieTask<T> addFailureListener(LottieListener<Throwable> listener);
227
public LottieTask<T> removeFailureListener(LottieListener<Throwable> listener);
228
229
// Static executor configuration
230
public static Executor EXECUTOR; // Default: cached thread pool
231
}
232
```
233
234
**Usage Examples:**
235
236
```java
237
// Chaining listeners
238
LottieCompositionFactory.fromAsset(context, "animation.json")
239
.addListener(composition -> {
240
// Success callback
241
animationView.setComposition(composition);
242
animationView.playAnimation();
243
})
244
.addFailureListener(throwable -> {
245
// Error callback
246
Log.e("Lottie", "Failed to load animation", throwable);
247
showErrorState();
248
})
249
.addListener(composition -> {
250
// Additional success callback
251
enableAnimationControls();
252
});
253
254
// Remove listeners
255
LottieListener<LottieComposition> listener = composition -> { /* ... */ };
256
LottieTask<LottieComposition> task = LottieCompositionFactory.fromAsset(context, "animation.json");
257
task.addListener(listener);
258
// Later...
259
task.removeListener(listener);
260
261
// Custom executor
262
LottieTask.EXECUTOR = Executors.newFixedThreadPool(2);
263
```
264
265
### LottieResult
266
267
Result wrapper containing either a success value or an exception. Used by synchronous loading methods.
268
269
```java { .api }
270
/**
271
* Result wrapper for sync operations
272
*/
273
public class LottieResult<V> {
274
public LottieResult(V value);
275
public LottieResult(Throwable exception);
276
277
public V getValue();
278
public Throwable getException();
279
280
@Override
281
public boolean equals(Object o);
282
@Override
283
public int hashCode();
284
}
285
```
286
287
**Usage Examples:**
288
289
```java
290
// Check result
291
LottieResult<LottieComposition> result =
292
LottieCompositionFactory.fromAssetSync(context, "animation.json");
293
294
if (result.getValue() != null) {
295
LottieComposition composition = result.getValue();
296
// Use composition
297
} else if (result.getException() != null) {
298
Throwable error = result.getException();
299
Log.e("Lottie", "Load failed", error);
300
}
301
```
302
303
## Network Loading Configuration
304
305
```java { .api }
306
public interface LottieNetworkFetcher {
307
LottieResult<LottieComposition> fetchSync(String url, String cacheKey);
308
}
309
310
public interface LottieNetworkCacheProvider {
311
File getCacheDir();
312
}
313
314
public interface LottieFetchResult {
315
boolean isSuccessful();
316
InputStream bodyByteStream();
317
String contentType();
318
}
319
320
public class DefaultLottieNetworkFetcher implements LottieNetworkFetcher {
321
public DefaultLottieNetworkFetcher();
322
public LottieResult<LottieComposition> fetchSync(String url, String cacheKey);
323
}
324
```