-
- All Implemented Interfaces:
-
android.graphics.drawable.Drawable.Callback,android.view.KeyEvent.Callback,android.view.accessibility.AccessibilityEventSource,androidx.core.view.TintableBackgroundView,androidx.core.widget.TintableImageSourceView
public class LottieAnimationView extends AppCompatImageView
This view will load, deserialize, and display an After Effects animation exported with bodymovin (github.com/airbnb/lottie-web).
You may set the animation in one of two ways: 1) Attrs: LottieAnimationView_lottie_fileName 2) Programmatically: setAnimationsetAnimationsetAnimationsetAnimationFromJsonsetAnimationFromUrlsetComposition
You can set a default cache strategy with lottie_cacheComposition.
You can manually set the progress of the animation with setProgress or lottie_progress
-
-
Field Summary
Fields Modifier and Type Field Description private LottieListener<Throwable>failureListenerprivate intfallbackResourceprivate booleancacheComposition
-
Constructor Summary
Constructors Constructor Description LottieAnimationView(Context context)LottieAnimationView(Context context, AttributeSet attrs)LottieAnimationView(Context context, AttributeSet attrs, int defStyleAttr)
-
Method Summary
Modifier and Type Method Description voidsetFailureListener(@Nullable() LottieListener<Throwable> failureListener)Set a default failure listener that will be called if any of the setAnimation APIs fail for any reason.This can be used to replace the default behavior. voidsetFallbackResource(@DrawableRes() int fallbackResource)Set a drawable that will be rendered if the LottieComposition fails to load for any reason. voidsetCacheComposition(boolean cacheComposition)If set to true, all future compositions that are set will be cached so that they don't need to be parsednext time they are loaded. voidsetImageResource(int resId)voidsetImageDrawable(Drawable drawable)voidsetImageBitmap(Bitmap bm)voidunscheduleDrawable(Drawable who)voidinvalidate()voidinvalidateDrawable(@NonNull() Drawable dr)voidsetIgnoreDisabledSystemAnimations(boolean ignore)Allows ignoring system animations settings, therefore allowing animations to run even if they are disabled. voidsetUseCompositionFrameRate(boolean useCompositionFrameRate)Lottie files can specify a target frame rate. voidenableMergePathsForKitKatAndAbove(boolean enable)Enable this to get merge path support for devices running KitKat (19) and above. booleanisMergePathsEnabledForKitKatAndAbove()Returns whether merge paths are enabled for KitKat and above. voidenableFeatureFlag(LottieFeatureFlag flag, boolean enable)Enable the specified feature for this LottieView. booleanisFeatureFlagEnabled(LottieFeatureFlag flag)Returns whether the specified feature is enabled. voidsetClipToCompositionBounds(boolean clipToCompositionBounds)Sets whether or not Lottie should clip to the original animation composition bounds. booleangetClipToCompositionBounds()Gets whether or not Lottie should clip to the original animation composition bounds. voidsetOutlineMasksAndMattes(boolean outline)Enable this to debug slow animations by outlining masks and mattes. voidsetAnimation(@RawRes() int rawRes)Sets the animation from a file in the raw directory.This will load and deserialize the file asynchronously. voidsetAnimation(String assetName)voidsetAnimationFromJson(String jsonString)voidsetAnimationFromJson(String jsonString, @Nullable() String cacheKey)Sets the animation from json string. voidsetAnimation(InputStream stream, @Nullable() String cacheKey)Sets the animation from an arbitrary InputStream.This will load and deserialize the file asynchronously. voidsetAnimation(ZipInputStream stream, @Nullable() String cacheKey)Sets the animation from a ZipInputStream.This will load and deserialize the file asynchronously. voidsetAnimationFromUrl(String url)Load a lottie animation from a url. voidsetAnimationFromUrl(String url, @Nullable() String cacheKey)Load a lottie animation from a url. voidsetComposition(@NonNull() LottieComposition composition)Sets a composition. LottieCompositiongetComposition()booleanhasMasks()Returns whether or not any layers in this composition has masks. booleanhasMatte()Returns whether or not any layers in this composition has a matte layer. voidplayAnimation()Plays the animation from the beginning. voidresumeAnimation()Continues playing the animation from its current position. voidsetMinFrame(int startFrame)Sets the minimum frame that the animation will start from when playing or looping. floatgetMinFrame()Returns the minimum frame set by setMinFrame or setMinProgress voidsetMinProgress(float startProgress)Sets the minimum progress that the animation will start from when playing or looping. voidsetMaxFrame(int endFrame)Sets the maximum frame that the animation will end at when playing or looping. floatgetMaxFrame()Returns the maximum frame set by setMaxFrame or setMaxProgress voidsetMaxProgress(@FloatRange(from = 0f, to = 1f) float endProgress)Sets the maximum progress that the animation will end at when playing or looping. voidsetMinFrame(String markerName)Sets the minimum frame to the start time of the specified marker. voidsetMaxFrame(String markerName)Sets the maximum frame to the start time + duration of the specified marker. voidsetMinAndMaxFrame(String markerName)Sets the minimum and maximum frame to the start time and start time + durationof the specified marker. voidsetMinAndMaxFrame(String startMarkerName, String endMarkerName, boolean playEndMarkerStartFrame)Sets the minimum and maximum frame to the start marker start and the maximum frame to the end marker start.playEndMarkerStartFrame determines whether or not to play the frame that the end marker is on. voidsetMinAndMaxFrame(int minFrame, int maxFrame)voidsetMinAndMaxProgress(@FloatRange(from = 0f, to = 1f) float minProgress, @FloatRange(from = 0f, to = 1f) float maxProgress)voidreverseAnimationSpeed()Reverses the current animation speed. voidsetSpeed(float speed)Sets the playback speed. floatgetSpeed()Returns the current playback speed. voidaddAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener)voidremoveUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener)voidremoveAllUpdateListeners()voidaddAnimatorListener(Animator.AnimatorListener listener)voidremoveAnimatorListener(Animator.AnimatorListener listener)voidremoveAllAnimatorListeners()voidaddAnimatorPauseListener(Animator.AnimatorPauseListener listener)voidremoveAnimatorPauseListener(Animator.AnimatorPauseListener listener)voidloop(boolean loop)voidsetRepeatMode(int mode)Defines what this animation should do when it reaches the end. intgetRepeatMode()Defines what this animation should do when it reaches the end. voidsetRepeatCount(int count)Sets how many times the animation should be repeated. intgetRepeatCount()Defines how many times the animation should repeat. booleanisAnimating()voidsetImageAssetsFolder(String imageAssetsFolder)If you use image assets, you must explicitly specify the folder in assets/ in which they arelocated because bodymovin uses the name filenames across all compositions (img_#).Do NOT rename the images themselves. StringgetImageAssetsFolder()voidsetMaintainOriginalImageBounds(boolean maintainOriginalImageBounds)When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size.When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds. booleangetMaintainOriginalImageBounds()When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size.When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds. BitmapupdateBitmap(String id, @Nullable() Bitmap bitmap)Allows you to modify or clear a bitmap that was loaded for an image either automaticallythrough setImageAssetsFolder or with an ImageAssetDelegate. voidsetImageAssetDelegate(ImageAssetDelegate assetDelegate)Use this if you can't bundle images with your app. voidsetDefaultFontFileExtension(String extension)By default, Lottie will look in src/assets/fonts/FONT_NAME.ttfwhere FONT_NAME is the fFamily specified in your Lottie file.If your fonts have a different extension, you can override thedefault here. voidsetFontAssetDelegate(FontAssetDelegate assetDelegate)Use this to manually set fonts. voidsetFontMap(@Nullable() Map<String, Typeface> fontMap)Set a map from font name keys to Typefaces.The keys can be in the form:* fontFamily* fontFamily-fontStyle* fontNameAll 3 are defined as fName, fFamily, and fStyle in the Lottie file. voidsetTextDelegate(TextDelegate textDelegate)Set this to replace animation text with custom text at runtime List<KeyPath>resolveKeyPath(KeyPath keyPath)Takes a KeyPath, potentially with wildcards or globstars and resolve it to a list ofzero or more actual Keypaths that exist in the current animation. <T> voidclearValueCallback(KeyPath keyPath, T property)Clear the value callback for all nodes that match the given KeyPath and property. <T> voidaddValueCallback(KeyPath keyPath, T property, LottieValueCallback<T> callback)Add a property callback for the specified KeyPath. <T> voidaddValueCallback(KeyPath keyPath, T property, SimpleLottieValueCallback<T> callback)Overload of addValueCallback that takes an interface. voidcancelAnimation()voidpauseAnimation()voidsetFrame(int frame)Sets the progress to the specified frame.If the composition isn't set yet, the progress will be set to the frame whenit is. intgetFrame()Get the currently rendered frame. voidsetProgress(@FloatRange(from = 0f, to = 1f) float progress)floatgetProgress()longgetDuration()voidsetPerformanceTrackingEnabled(boolean enabled)PerformanceTrackergetPerformanceTracker()voidsetSafeMode(boolean safeMode)If you are experiencing a device specific crash that happens during drawing, you can set this to truefor those devices. voidsetRenderMode(RenderMode renderMode)Call this to set whether or not to render with hardware or software acceleration.Lottie defaults to Automatic which will use hardware acceleration unless:1) There are dash paths and the device is pre-Pie.2) There are more than 4 masks and mattes.Hardware acceleration is generally faster for those devices unlessthere are many large mattes and masks in which case there is a lotof GPU uploadTexture thrashing which makes it much slower. RenderModegetRenderMode()Returns the actual render mode being used. AsyncUpdatesgetAsyncUpdates()Returns the current value of AsyncUpdates. booleangetAsyncUpdatesEnabled()Similar to getAsyncUpdates except it returns the actualboolean value for whether async updates are enabled or not. voidsetAsyncUpdates(AsyncUpdates asyncUpdates)**Note: this API is experimental and may changed. voidsetApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled)Sets whether to apply opacity to the each layer instead of shape. voidsetApplyingShadowToLayersEnabled(boolean isApplyingShadowToLayersEnabled)Sets whether to apply drop shadows to each layer instead of shape. booleangetClipTextToBoundingBox()voidsetClipTextToBoundingBox(boolean clipTextToBoundingBox)When true, if there is a bounding box set on a text layer (paragraph text), any textthat overflows past its height will not be drawn. voiddisableExtraScaleModeInFitXY()This API no longer has any effect. booleanaddLottieOnCompositionLoadedListener(@NonNull() LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener)booleanremoveLottieOnCompositionLoadedListener(@NonNull() LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener)voidremoveAllLottieOnCompositionLoadedListener()-
Methods inherited from class androidx.appcompat.widget.AppCompatImageView
getSupportBackgroundTintList, getSupportBackgroundTintMode, getSupportImageTintList, getSupportImageTintMode, hasOverlappingRendering, setBackgroundDrawable, setBackgroundResource, setImageBitmap, setImageDrawable, setImageLevel, setImageResource, setImageURI, setSupportBackgroundTintList, setSupportBackgroundTintMode, setSupportImageTintList, setSupportImageTintMode -
Methods inherited from class android.widget.ImageView
animateTransform, clearColorFilter, drawableHotspotChanged, getAccessibilityClassName, getAdjustViewBounds, getBaseline, getBaselineAlignBottom, getColorFilter, getCropToPadding, getDrawable, getImageAlpha, getImageMatrix, getImageTintBlendMode, getImageTintList, getImageTintMode, getMaxHeight, getMaxWidth, getScaleType, invalidateDrawable, isOpaque, jumpDrawablesToCurrentState, onCreateDrawableState, onRtlPropertiesChanged, onVisibilityAggregated, setAdjustViewBounds, setAlpha, setBaseline, setBaselineAlignBottom, setColorFilter, setCropToPadding, setImageAlpha, setImageIcon, setImageMatrix, setImageState, setImageTintBlendMode, setImageTintList, setImageTintMode, setMaxHeight, setMaxWidth, setScaleType, setSelected, setVisibility -
Methods inherited from class android.view.View
addChildrenForAccessibility, addExtraDataToAccessibilityNodeInfo, addFocusables, addKeyboardNavigationClusters, addOnAttachStateChangeListener, addOnLayoutChangeListener, addOnUnhandledKeyEventListener, addTouchables, animate, announceForAccessibility, autofill, bringToFront, buildDrawingCache, buildLayer, callOnClick, canResolveLayoutDirection, canResolveTextAlignment, canResolveTextDirection, canScrollHorizontally, canScrollVertically, cancelDragAndDrop, cancelLongPress, cancelPendingInputEvents, checkInputConnectionProxy, clearAnimation, clearFocus, clearViewTranslationCallback, combineMeasuredStates, computeScroll, computeSystemWindowInsets, createAccessibilityNodeInfo, createContextMenu, destroyDrawingCache, dispatchApplyWindowInsets, dispatchCapturedPointerEvent, dispatchConfigurationChanged, dispatchCreateViewTranslationRequest, dispatchDisplayHint, dispatchDragEvent, dispatchDrawableHotspotChanged, dispatchFinishTemporaryDetach, dispatchGenericMotionEvent, dispatchKeyEvent, dispatchKeyEventPreIme, dispatchKeyShortcutEvent, dispatchNestedFling, dispatchNestedPreFling, dispatchNestedPrePerformAccessibilityAction, dispatchNestedPreScroll, dispatchNestedScroll, dispatchPointerCaptureChanged, dispatchPopulateAccessibilityEvent, dispatchProvideAutofillStructure, dispatchProvideStructure, dispatchScrollCaptureSearch, dispatchStartTemporaryDetach, dispatchSystemUiVisibilityChanged, dispatchTouchEvent, dispatchTrackballEvent, dispatchUnhandledMove, dispatchWindowFocusChanged, dispatchWindowInsetsAnimationEnd, dispatchWindowInsetsAnimationPrepare, dispatchWindowInsetsAnimationProgress, dispatchWindowInsetsAnimationStart, dispatchWindowSystemUiVisiblityChanged, dispatchWindowVisibilityChanged, draw, findFocus, findOnBackInvokedDispatcher, findViewById, findViewWithTag, findViewsWithText, focusSearch, forceHasOverlappingRendering, forceLayout, gatherTransparentRegion, generateDisplayHash, generateViewId, getAccessibilityDelegate, getAccessibilityLiveRegion, getAccessibilityNodeProvider, getAccessibilityPaneTitle, getAccessibilityTraversalAfter, getAccessibilityTraversalBefore, getAllowedHandwritingDelegatePackageName, getAllowedHandwritingDelegatorPackageName, getAlpha, getAnimation, getAnimationMatrix, getApplicationWindowToken, getAttributeResolutionStack, getAttributeSourceResourceMap, getAutofillHints, getAutofillId, getAutofillType, getAutofillValue, getBackground, getBackgroundTintBlendMode, getBackgroundTintList, getBackgroundTintMode, getBottom, getCameraDistance, getClipBounds, getClipBounds, getClipToOutline, getContentCaptureSession, getContentDescription, getContext, getDefaultFocusHighlightEnabled, getDefaultSize, getDisplay, getDrawableState, getDrawingCache, getDrawingCacheBackgroundColor, getDrawingCacheQuality, getDrawingRect, getDrawingTime, getElevation, getExplicitStyle, getFilterTouchesWhenObscured, getFitsSystemWindows, getFocusable, getFocusables, getFocusedRect, getForeground, getForegroundGravity, getForegroundTintBlendMode, getForegroundTintList, getForegroundTintMode, getGlobalVisibleRect, getHandler, getHandwritingBoundsOffsetBottom, getHandwritingBoundsOffsetLeft, getHandwritingBoundsOffsetRight, getHandwritingBoundsOffsetTop, getHandwritingDelegatorCallback, getHasOverlappingRendering, getHeight, getHitRect, getHorizontalFadingEdgeLength, getHorizontalScrollbarThumbDrawable, getHorizontalScrollbarTrackDrawable, getId, getImportantForAccessibility, getImportantForAutofill, getImportantForContentCapture, getKeepScreenOn, getKeyDispatcherState, getLabelFor, getLayerType, getLayoutDirection, getLayoutParams, getLeft, getLocalVisibleRect, getLocationInSurface, getLocationInWindow, getLocationOnScreen, getMatrix, getMeasuredHeight, getMeasuredHeightAndState, getMeasuredState, getMeasuredWidth, getMeasuredWidthAndState, getMinimumHeight, getMinimumWidth, getNextClusterForwardId, getNextFocusDownId, getNextFocusForwardId, getNextFocusLeftId, getNextFocusRightId, getNextFocusUpId, getOnFocusChangeListener, getOutlineAmbientShadowColor, getOutlineProvider, getOutlineSpotShadowColor, getOverScrollMode, getOverlay, getPaddingBottom, getPaddingEnd, getPaddingLeft, getPaddingRight, getPaddingStart, getPaddingTop, getParent, getParentForAccessibility, getPivotX, getPivotY, getPointerIcon, getPreferKeepClearRects, getReceiveContentMimeTypes, getResources, getRevealOnFocusHint, getRight, getRootSurfaceControl, getRootView, getRootWindowInsets, getRotation, getRotationX, getRotationY, getScaleX, getScaleY, getScrollBarDefaultDelayBeforeFade, getScrollBarFadeDuration, getScrollBarSize, getScrollBarStyle, getScrollCaptureHint, getScrollIndicators, getScrollX, getScrollY, getSolidColor, getSourceLayoutResId, getStateDescription, getStateListAnimator, getSystemGestureExclusionRects, getSystemUiVisibility, getTag, getTextAlignment, getTextDirection, getTooltipText, getTop, getTouchDelegate, getTouchables, getTransitionAlpha, getTransitionName, getTranslationX, getTranslationY, getTranslationZ, getUniqueDrawingId, getVerticalFadingEdgeLength, getVerticalScrollbarPosition, getVerticalScrollbarThumbDrawable, getVerticalScrollbarTrackDrawable, getVerticalScrollbarWidth, getViewTranslationResponse, getViewTreeObserver, getVisibility, getWidth, getWindowId, getWindowInsetsController, getWindowSystemUiVisibility, getWindowToken, getWindowVisibility, getWindowVisibleDisplayFrame, getX, getY, getZ, hasExplicitFocusable, hasFocus, hasFocusable, hasNestedScrollingParent, hasOnClickListeners, hasOnLongClickListeners, hasPointerCapture, hasTransientState, hasWindowFocus, inflate, invalidate, invalidateOutline, isAccessibilityDataSensitive, isAccessibilityFocused, isAccessibilityHeading, isActivated, isAttachedToWindow, isAutoHandwritingEnabled, isClickable, isContextClickable, isCredential, isDirty, isDrawingCacheEnabled, isDuplicateParentStateEnabled, isEnabled, isFocusable, isFocusableInTouchMode, isFocused, isFocusedByDefault, isForceDarkAllowed, isHandwritingDelegate, isHapticFeedbackEnabled, isHardwareAccelerated, isHorizontalFadingEdgeEnabled, isHorizontalScrollBarEnabled, isHovered, isImportantForAccessibility, isImportantForAutofill, isImportantForContentCapture, isInEditMode, isInLayout, isInTouchMode, isKeyboardNavigationCluster, isLaidOut, isLayoutDirectionResolved, isLayoutRequested, isLongClickable, isNestedScrollingEnabled, isPaddingRelative, isPivotSet, isPreferKeepClear, isPressed, isSaveEnabled, isSaveFromParentEnabled, isScreenReaderFocusable, isScrollContainer, isScrollbarFadingEnabled, isSelected, isShowingLayoutBounds, isShown, isSoundEffectsEnabled, isTemporarilyDetached, isTextAlignmentResolved, isTextDirectionResolved, isVerticalFadingEdgeEnabled, isVerticalScrollBarEnabled, isVisibleToUserForAutofill, keyboardNavigationClusterSearch, layout, measure, offsetLeftAndRight, offsetTopAndBottom, onApplyWindowInsets, onCancelPendingInputEvents, onCapturedPointerEvent, onCheckIsTextEditor, onCreateInputConnection, onCreateViewTranslationRequest, onCreateVirtualViewTranslationRequests, onDragEvent, onDrawForeground, onFilterTouchEventForSecurity, onFinishTemporaryDetach, onGenericMotionEvent, onHoverChanged, onHoverEvent, onInitializeAccessibilityEvent, onInitializeAccessibilityNodeInfo, onKeyDown, onKeyLongPress, onKeyMultiple, onKeyPreIme, onKeyShortcut, onKeyUp, onPointerCaptureChange, onPopulateAccessibilityEvent, onProvideAutofillStructure, onProvideAutofillVirtualStructure, onProvideContentCaptureStructure, onProvideStructure, onProvideVirtualStructure, onReceiveContent, onResolvePointerIcon, onScreenStateChanged, onScrollCaptureSearch, onStartTemporaryDetach, onTouchEvent, onTrackballEvent, onViewTranslationResponse, onVirtualViewTranslationResponses, onWindowFocusChanged, onWindowSystemUiVisibilityChanged, performAccessibilityAction, performClick, performContextClick, performHapticFeedback, performLongClick, performReceiveContent, playSoundEffect, post, postDelayed, postInvalidate, postInvalidateDelayed, postInvalidateOnAnimation, postOnAnimation, postOnAnimationDelayed, refreshDrawableState, releasePointerCapture, removeCallbacks, removeOnAttachStateChangeListener, removeOnLayoutChangeListener, removeOnUnhandledKeyEventListener, requestApplyInsets, requestFitSystemWindows, requestFocus, requestFocusFromTouch, requestLayout, requestPointerCapture, requestRectangleOnScreen, requestUnbufferedDispatch, requireViewById, resetPivot, resolveSize, resolveSizeAndState, restoreDefaultFocus, restoreHierarchyState, saveAttributeDataForStyleable, saveHierarchyState, scheduleDrawable, scrollBy, scrollTo, sendAccessibilityEvent, sendAccessibilityEventUnchecked, setAccessibilityDataSensitive, setAccessibilityDelegate, setAccessibilityHeading, setAccessibilityLiveRegion, setAccessibilityPaneTitle, setAccessibilityTraversalAfter, setAccessibilityTraversalBefore, setActivated, setAllowClickWhenDisabled, setAllowedHandwritingDelegatePackage, setAllowedHandwritingDelegatorPackage, setAnimation, setAnimationMatrix, setAutoHandwritingEnabled, setAutofillHints, setAutofillId, setBackground, setBackgroundColor, setBackgroundTintBlendMode, setBackgroundTintList, setBackgroundTintMode, setBottom, setCameraDistance, setClickable, setClipBounds, setClipToOutline, setContentCaptureSession, setContentDescription, setContextClickable, setDefaultFocusHighlightEnabled, setDrawingCacheBackgroundColor, setDrawingCacheEnabled, setDrawingCacheQuality, setDuplicateParentStateEnabled, setElevation, setEnabled, setFadingEdgeLength, setFilterTouchesWhenObscured, setFitsSystemWindows, setFocusable, setFocusableInTouchMode, setFocusedByDefault, setForceDarkAllowed, setForeground, setForegroundGravity, setForegroundTintBlendMode, setForegroundTintList, setForegroundTintMode, setHandwritingBoundsOffsets, setHandwritingDelegatorCallback, setHapticFeedbackEnabled, setHasTransientState, setHorizontalFadingEdgeEnabled, setHorizontalScrollBarEnabled, setHorizontalScrollbarThumbDrawable, setHorizontalScrollbarTrackDrawable, setHovered, setId, setImportantForAccessibility, setImportantForAutofill, setImportantForContentCapture, setIsCredential, setIsHandwritingDelegate, setKeepScreenOn, setKeyboardNavigationCluster, setLabelFor, setLayerPaint, setLayerType, setLayoutDirection, setLayoutParams, setLeft, setLeftTopRightBottom, setLongClickable, setMinimumHeight, setMinimumWidth, setNestedScrollingEnabled, setNextClusterForwardId, setNextFocusDownId, setNextFocusForwardId, setNextFocusLeftId, setNextFocusRightId, setNextFocusUpId, setOnApplyWindowInsetsListener, setOnCapturedPointerListener, setOnClickListener, setOnContextClickListener, setOnCreateContextMenuListener, setOnDragListener, setOnFocusChangeListener, setOnGenericMotionListener, setOnHoverListener, setOnKeyListener, setOnLongClickListener, setOnReceiveContentListener, setOnScrollChangeListener, setOnSystemUiVisibilityChangeListener, setOnTouchListener, setOutlineAmbientShadowColor, setOutlineProvider, setOutlineSpotShadowColor, setOverScrollMode, setPadding, setPaddingRelative, setPivotX, setPivotY, setPointerIcon, setPreferKeepClear, setPreferKeepClearRects, setPressed, setRenderEffect, setRevealOnFocusHint, setRight, setRotation, setRotationX, setRotationY, setSaveEnabled, setSaveFromParentEnabled, setScaleX, setScaleY, setScreenReaderFocusable, setScrollBarDefaultDelayBeforeFade, setScrollBarFadeDuration, setScrollBarSize, setScrollBarStyle, setScrollCaptureCallback, setScrollCaptureHint, setScrollContainer, setScrollIndicators, setScrollX, setScrollY, setScrollbarFadingEnabled, setSoundEffectsEnabled, setStateDescription, setStateListAnimator, setSystemGestureExclusionRects, setSystemUiVisibility, setTag, setTextAlignment, setTextDirection, setTooltipText, setTop, setTouchDelegate, setTransitionAlpha, setTransitionName, setTransitionVisibility, setTranslationX, setTranslationY, setTranslationZ, setVerticalFadingEdgeEnabled, setVerticalScrollBarEnabled, setVerticalScrollbarPosition, setVerticalScrollbarThumbDrawable, setVerticalScrollbarTrackDrawable, setViewTranslationCallback, setWillNotCacheDrawing, setWillNotDraw, setWindowInsetsAnimationCallback, setX, setY, setZ, showContextMenu, startActionMode, startAnimation, startDrag, startDragAndDrop, startNestedScroll, stopNestedScroll, toString, transformMatrixToGlobal, transformMatrixToLocal, unscheduleDrawable, updateDragShadow, willNotCacheDrawing, willNotDraw -
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
-
Constructor Detail
-
LottieAnimationView
LottieAnimationView(Context context)
-
LottieAnimationView
LottieAnimationView(Context context, AttributeSet attrs)
-
LottieAnimationView
LottieAnimationView(Context context, AttributeSet attrs, int defStyleAttr)
-
-
Method Detail
-
setFailureListener
void setFailureListener(@Nullable() LottieListener<Throwable> failureListener)
Set a default failure listener that will be called if any of the setAnimation APIs fail for any reason.This can be used to replace the default behavior.
The default behavior will log any network errors and rethrow all other exceptions.
If you are loading an animation from the network, errors may occur if your user has no internet.You can use this listener to retry the download or you can have it default to an error drawablewith setFallbackResource.
Unless you are using setAnimationFromUrl, errors are unexpected.
Set the listener to null to revert to the default behavior.
-
setFallbackResource
void setFallbackResource(@DrawableRes() int fallbackResource)
Set a drawable that will be rendered if the LottieComposition fails to load for any reason.Unless you are using setAnimationFromUrl, this is an unexpected error andyou should handle it with setFailureListener.
If this is a network animation, you may use this to show an error to the user oryou can use a failure listener to retry the download.
-
setCacheComposition
void setCacheComposition(boolean cacheComposition)
If set to true, all future compositions that are set will be cached so that they don't need to be parsednext time they are loaded. This won't apply to compositions that have already been loaded.
Defaults to true.
lottie_cacheComposition
-
setImageResource
void setImageResource(int resId)
-
setImageDrawable
void setImageDrawable(Drawable drawable)
-
setImageBitmap
void setImageBitmap(Bitmap bm)
-
unscheduleDrawable
void unscheduleDrawable(Drawable who)
-
invalidate
void invalidate()
-
invalidateDrawable
void invalidateDrawable(@NonNull() Drawable dr)
-
setIgnoreDisabledSystemAnimations
@Deprecated() void setIgnoreDisabledSystemAnimations(boolean ignore)
Allows ignoring system animations settings, therefore allowing animations to run even if they are disabled.
Defaults to false.
- Parameters:
ignore- if true animations will run even when they are disabled in the system settings.
-
setUseCompositionFrameRate
void setUseCompositionFrameRate(boolean useCompositionFrameRate)
Lottie files can specify a target frame rate. By default, Lottie ignores it and re-renderson every frame. If that behavior is undesirable, you can set this to true to use the compositionframe rate instead.
Note: composition frame rates are usually lower than display frame ratesso this will likely make your animation feel janky. However, it may be desirablefor specific situations such as pixel art that are intended to have low frame rates.
-
enableMergePathsForKitKatAndAbove
void enableMergePathsForKitKatAndAbove(boolean enable)
Enable this to get merge path support for devices running KitKat (19) and above.
Merge paths currently don't work if the the operand shape is entirely contained within thefirst shape. If you need to cut out one shape from another shape, use an even-odd fill typeinstead of using merge paths.
-
isMergePathsEnabledForKitKatAndAbove
boolean isMergePathsEnabledForKitKatAndAbove()
Returns whether merge paths are enabled for KitKat and above.
-
enableFeatureFlag
void enableFeatureFlag(LottieFeatureFlag flag, boolean enable)
Enable the specified feature for this LottieView.
Features guarded by LottieFeatureFlags are experimental or only supported by a subset of API levels.Please ensure that the animation supported by the enabled feature looks acceptable across alltargeted API levels.
-
isFeatureFlagEnabled
boolean isFeatureFlagEnabled(LottieFeatureFlag flag)
Returns whether the specified feature is enabled.
-
setClipToCompositionBounds
void setClipToCompositionBounds(boolean clipToCompositionBounds)
Sets whether or not Lottie should clip to the original animation composition bounds.
When set to true, the parent view may need to disable clipChildren so Lottie can render outside of the LottieAnimationView bounds.
Defaults to true.
-
getClipToCompositionBounds
boolean getClipToCompositionBounds()
Gets whether or not Lottie should clip to the original animation composition bounds.
Defaults to true.
-
setOutlineMasksAndMattes
void setOutlineMasksAndMattes(boolean outline)
Enable this to debug slow animations by outlining masks and mattes. The performance overhead of the masks and mattes willbe proportional to the surface area of all of the masks/mattes combined.
DO NOT leave this enabled in production.
-
setAnimation
void setAnimation(@RawRes() int rawRes)
Sets the animation from a file in the raw directory.This will load and deserialize the file asynchronously.
-
setAnimation
void setAnimation(String assetName)
-
setAnimationFromJson
@Deprecated() void setAnimationFromJson(String jsonString)
-
setAnimationFromJson
void setAnimationFromJson(String jsonString, @Nullable() String cacheKey)
Sets the animation from json string. This is the ideal API to use when loading an animationover the network because you can use the raw response body here and a conversion to aJSONObject never has to be done.
-
setAnimation
void setAnimation(InputStream stream, @Nullable() String cacheKey)
Sets the animation from an arbitrary InputStream.This will load and deserialize the file asynchronously.
If this is a Zip file, wrap your InputStream with a ZipInputStream to use the overloaddesigned for zip files.
This is particularly useful for animations loaded from the network. You can fetch thebodymovin json from the network and pass it directly here.
Auto-closes the stream.
-
setAnimation
void setAnimation(ZipInputStream stream, @Nullable() String cacheKey)
Sets the animation from a ZipInputStream.This will load and deserialize the file asynchronously.
This is particularly useful for animations loaded from the network. You can fetch thebodymovin json from the network and pass it directly here.
Auto-closes the stream.
-
setAnimationFromUrl
void setAnimationFromUrl(String url)
Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together andlottiewill unzip and link the images automatically.
Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the fileto the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one thatcan be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted.
You can replace the default network stack or cache handling with a global LottieConfig
-
setAnimationFromUrl
void setAnimationFromUrl(String url, @Nullable() String cacheKey)
Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together andlottiewill unzip and link the images automatically.
Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the fileto the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one thatcan be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted.
You can replace the default network stack or cache handling with a global LottieConfig
-
setComposition
void setComposition(@NonNull() LottieComposition composition)
Sets a composition.You can set a default cache strategy if this view was inflated with xml byusing lottie_cacheComposition.
-
getComposition
@Nullable() LottieComposition getComposition()
-
hasMasks
boolean hasMasks()
Returns whether or not any layers in this composition has masks.
-
hasMatte
boolean hasMatte()
Returns whether or not any layers in this composition has a matte layer.
-
playAnimation
@MainThread() void playAnimation()
Plays the animation from the beginning. If speed is
{@literal <}0, it will start at the endand play towards the beginning
-
resumeAnimation
@MainThread() void resumeAnimation()
Continues playing the animation from its current position. If speed
{@literal <}0, it will play backwardsfrom the current position.
-
setMinFrame
void setMinFrame(int startFrame)
Sets the minimum frame that the animation will start from when playing or looping.
-
getMinFrame
float getMinFrame()
Returns the minimum frame set by setMinFrame or setMinProgress
-
setMinProgress
void setMinProgress(float startProgress)
Sets the minimum progress that the animation will start from when playing or looping.
-
setMaxFrame
void setMaxFrame(int endFrame)
Sets the maximum frame that the animation will end at when playing or looping.
The value will be clamped to the composition bounds. For example, setting Integer.MAX_VALUE would result in the samething as composition.endFrame.
-
getMaxFrame
float getMaxFrame()
Returns the maximum frame set by setMaxFrame or setMaxProgress
-
setMaxProgress
void setMaxProgress(@FloatRange(from = 0f, to = 1f) float endProgress)
Sets the maximum progress that the animation will end at when playing or looping.
-
setMinFrame
void setMinFrame(String markerName)
Sets the minimum frame to the start time of the specified marker.
-
setMaxFrame
void setMaxFrame(String markerName)
Sets the maximum frame to the start time + duration of the specified marker.
-
setMinAndMaxFrame
void setMinAndMaxFrame(String markerName)
Sets the minimum and maximum frame to the start time and start time + durationof the specified marker.
-
setMinAndMaxFrame
void setMinAndMaxFrame(String startMarkerName, String endMarkerName, boolean playEndMarkerStartFrame)
Sets the minimum and maximum frame to the start marker start and the maximum frame to the end marker start.playEndMarkerStartFrame determines whether or not to play the frame that the end marker is on. If the end markerrepresents the end of the section that you want, it should be true. If the marker represents the beginning of thenext section, it should be false.
-
setMinAndMaxFrame
void setMinAndMaxFrame(int minFrame, int maxFrame)
-
setMinAndMaxProgress
void setMinAndMaxProgress(@FloatRange(from = 0f, to = 1f) float minProgress, @FloatRange(from = 0f, to = 1f) float maxProgress)
-
reverseAnimationSpeed
void reverseAnimationSpeed()
Reverses the current animation speed. This does NOT play the animation.
-
setSpeed
void setSpeed(float speed)
Sets the playback speed. If speed
{@literal <}0, the animation will play backwards.
-
getSpeed
float getSpeed()
Returns the current playback speed. This will be
{@literal <}0 if the animation is playing backwards.
-
addAnimatorUpdateListener
void addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener)
-
removeUpdateListener
void removeUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener)
-
removeAllUpdateListeners
void removeAllUpdateListeners()
-
addAnimatorListener
void addAnimatorListener(Animator.AnimatorListener listener)
-
removeAnimatorListener
void removeAnimatorListener(Animator.AnimatorListener listener)
-
removeAllAnimatorListeners
void removeAllAnimatorListeners()
-
addAnimatorPauseListener
@RequiresApi(api = Build.VERSION_CODES.KITKAT) void addAnimatorPauseListener(Animator.AnimatorPauseListener listener)
-
removeAnimatorPauseListener
@RequiresApi(api = Build.VERSION_CODES.KITKAT) void removeAnimatorPauseListener(Animator.AnimatorPauseListener listener)
-
loop
@Deprecated() void loop(boolean loop)
-
setRepeatMode
void setRepeatMode(int mode)
-
getRepeatMode
int getRepeatMode()
Defines what this animation should do when it reaches the end.
-
setRepeatCount
void setRepeatCount(int count)
Sets how many times the animation should be repeated. If the repeatcount is 0, the animation is never repeated. If the repeat count isgreater than 0 or INFINITE, the repeat mode will be takeninto account. The repeat count is 0 by default.
- Parameters:
count- the number of times the animation should be repeated
-
getRepeatCount
int getRepeatCount()
Defines how many times the animation should repeat. The default valueis 0.
-
isAnimating
boolean isAnimating()
-
setImageAssetsFolder
void setImageAssetsFolder(String imageAssetsFolder)
If you use image assets, you must explicitly specify the folder in assets/ in which they arelocated because bodymovin uses the name filenames across all compositions (img_#).Do NOT rename the images themselves.
If your images are located in src/main/assets/airbnb_loader/ then call`setImageAssetsFolder("airbnb_loader/");`.
Be wary if you are using many images, however. Lottie is designed to work with vector shapesfrom After Effects. If your images look like they could be represented with vector shapes,see if it is possible to convert them to shape layers and re-export your animation. Checkthe documentation at airbnb.io/lottie for more information about importing shapes fromSketch or Illustrator to avoid this.
-
getImageAssetsFolder
@Nullable() String getImageAssetsFolder()
-
setMaintainOriginalImageBounds
void setMaintainOriginalImageBounds(boolean maintainOriginalImageBounds)
When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size.When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds.
Defaults to false.
-
getMaintainOriginalImageBounds
boolean getMaintainOriginalImageBounds()
When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size.When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds.
Defaults to false.
-
updateBitmap
@Nullable() Bitmap updateBitmap(String id, @Nullable() Bitmap bitmap)
Allows you to modify or clear a bitmap that was loaded for an image either automaticallythrough setImageAssetsFolder or with an ImageAssetDelegate.
-
setImageAssetDelegate
void setImageAssetDelegate(ImageAssetDelegate assetDelegate)
Use this if you can't bundle images with your app. This may be useful if you download theanimations from the network or have the images saved to an SD Card. In that case, Lottiewill defer the loading of the bitmap to this delegate.
Be wary if you are using many images, however. Lottie is designed to work with vector shapesfrom After Effects. If your images look like they could be represented with vector shapes,see if it is possible to convert them to shape layers and re-export your animation. Checkthe documentation at airbnb.io/lottie for more information about importing shapes fromSketch or Illustrator to avoid this.
-
setDefaultFontFileExtension
void setDefaultFontFileExtension(String extension)
By default, Lottie will look in src/assets/fonts/FONT_NAME.ttfwhere FONT_NAME is the fFamily specified in your Lottie file.If your fonts have a different extension, you can override thedefault here.
Alternatively, you can use setFontAssetDelegate for more control.
-
setFontAssetDelegate
void setFontAssetDelegate(FontAssetDelegate assetDelegate)
Use this to manually set fonts.
-
setFontMap
void setFontMap(@Nullable() Map<String, Typeface> fontMap)
Set a map from font name keys to Typefaces.The keys can be in the form:* fontFamily* fontFamily-fontStyle* fontNameAll 3 are defined as fName, fFamily, and fStyle in the Lottie file.
If you change a value in fontMap, create a new map or call invalidate. Setting the same map again will noop.
-
setTextDelegate
void setTextDelegate(TextDelegate textDelegate)
Set this to replace animation text with custom text at runtime
-
resolveKeyPath
List<KeyPath> resolveKeyPath(KeyPath keyPath)
Takes a KeyPath, potentially with wildcards or globstars and resolve it to a list ofzero or more actual Keypaths that exist in the current animation.
If you want to set value callbacks for any of these values, it is recommended to use thereturned KeyPath objects because they will be internally resolved to their contentand won't trigger a tree walk of the animation contents when applied.
-
clearValueCallback
<T> void clearValueCallback(KeyPath keyPath, T property)
Clear the value callback for all nodes that match the given KeyPath and property.
-
addValueCallback
<T> void addValueCallback(KeyPath keyPath, T property, LottieValueCallback<T> callback)
Add a property callback for the specified KeyPath. This KeyPath can resolveto multiple contents. In that case, the callback's value will apply to all of them.
Internally, this will check if the KeyPath has already been resolved with resolveKeyPath and will resolve it if it hasn't.
-
addValueCallback
<T> void addValueCallback(KeyPath keyPath, T property, SimpleLottieValueCallback<T> callback)
Overload of addValueCallback that takes an interface. This allows you to use a single abstractmethod code block in Kotlin such as:animationView.addValueCallback(yourKeyPath, LottieProperty.COLOR) { yourColor }
-
cancelAnimation
@MainThread() void cancelAnimation()
-
pauseAnimation
@MainThread() void pauseAnimation()
-
setFrame
void setFrame(int frame)
Sets the progress to the specified frame.If the composition isn't set yet, the progress will be set to the frame whenit is.
-
getFrame
int getFrame()
Get the currently rendered frame.
-
setProgress
void setProgress(@FloatRange(from = 0f, to = 1f) float progress)
-
getProgress
@FloatRange(from = 0.0f, to = 1.0f) float getProgress()
-
getDuration
long getDuration()
-
setPerformanceTrackingEnabled
void setPerformanceTrackingEnabled(boolean enabled)
-
getPerformanceTracker
@Nullable() PerformanceTracker getPerformanceTracker()
-
setSafeMode
void setSafeMode(boolean safeMode)
If you are experiencing a device specific crash that happens during drawing, you can set this to truefor those devices. If set to true, draw will be wrapped with a try/catch which will cause Lottie torender an empty frame rather than crash your app.
Ideally, you will never need this and the vast majority of apps and animations won't. However, you may usethis for very specific cases if absolutely necessary.
There is no XML attr for this because it should be set programmatically and only for specific devices thatare known to be problematic.
-
setRenderMode
void setRenderMode(RenderMode renderMode)
Call this to set whether or not to render with hardware or software acceleration.Lottie defaults to Automatic which will use hardware acceleration unless:1) There are dash paths and the device is pre-Pie.2) There are more than 4 masks and mattes.Hardware acceleration is generally faster for those devices unlessthere are many large mattes and masks in which case there is a lotof GPU uploadTexture thrashing which makes it much slower.
In most cases, hardware rendering will be faster, even if you have mattes and masks.However, if you have multiple mattes and masks (especially large ones), youshould test both render modes. You should also test on pre-Pie and Pie+ devicesbecause the underlying rendering engine changed significantly.
-
getRenderMode
RenderMode getRenderMode()
Returns the actual render mode being used. It will always be HARDWARE or SOFTWARE.When the render mode is set to AUTOMATIC, the value will be derived from useSoftwareRendering.
-
getAsyncUpdates
AsyncUpdates getAsyncUpdates()
Returns the current value of AsyncUpdates. Refer to the docs for AsyncUpdates for more info.
-
getAsyncUpdatesEnabled
boolean getAsyncUpdatesEnabled()
Similar to getAsyncUpdates except it returns the actualboolean value for whether async updates are enabled or not.
-
setAsyncUpdates
void setAsyncUpdates(AsyncUpdates asyncUpdates)
**Note: this API is experimental and may changed.**
Sets the current value for AsyncUpdates. Refer to the docs for AsyncUpdates for more info.
-
setApplyingOpacityToLayersEnabled
void setApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled)
Sets whether to apply opacity to the each layer instead of shape.
Opacity is normally applied directly to a shape. In cases where translucent shapes overlap, applying opacity to a layer will be more accurateat the expense of performance.
The default value is false.
Note: This process is very expensive. The performance impact will be reduced when hardware acceleration is enabled.
-
setApplyingShadowToLayersEnabled
void setApplyingShadowToLayersEnabled(boolean isApplyingShadowToLayersEnabled)
Sets whether to apply drop shadows to each layer instead of shape.
When true, the behavior will be more correct: it will mimic lottie-web and other renderers, in that drop shadows will be applied to a layeras a whole, no matter its contents.
When false, the performance will be better at the expense of correctness: for each shape element individually, the first drop shadow upwardsin the hierarchy is applied to it directly. Visually, this may manifest as phantom shadows or artifacts where the artist has intended to treat alayer as a whole, and this option exposes its internal structure.
The default value is true.
-
getClipTextToBoundingBox
boolean getClipTextToBoundingBox()
-
setClipTextToBoundingBox
void setClipTextToBoundingBox(boolean clipTextToBoundingBox)
When true, if there is a bounding box set on a text layer (paragraph text), any textthat overflows past its height will not be drawn.
-
disableExtraScaleModeInFitXY
@Deprecated() void disableExtraScaleModeInFitXY()
This API no longer has any effect.
-
addLottieOnCompositionLoadedListener
boolean addLottieOnCompositionLoadedListener(@NonNull() LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener)
-
removeLottieOnCompositionLoadedListener
boolean removeLottieOnCompositionLoadedListener(@NonNull() LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener)
-
removeAllLottieOnCompositionLoadedListener
void removeAllLottieOnCompositionLoadedListener()
-
-
-
-