Upgrade to Pro — share decks privately, control downloads, hide ads and more …

I Can Animate and So Can You

I Can Animate and So Can You

A talk about View animations on Android.

Original Keynote files (with animations): https://db.tt/qnUnoHpF

Daniel Lew

November 15, 2013
Tweet

More Decks by Daniel Lew

Other Decks in Programming

Transcript

  1. Building Animations • Figure out what attributes to animate •

    Design View hierarchy • Measure attribute start/ end values • Setup and run animators
  2. View Attributes • Basic animation attributes • Translation • Scale

    • Rotation • Alpha • Custom attributes can be added
  3. Determining Attributes • Alpha - every element • Translate -

    every row • Translate - details header/footer • Scale - details rows (a hardcore fake) • Fading background - not needed!
  4. View Hierarchy • Animation informs View hierarchy • Rows go

    underneath split action bar • Classic problem: Views cannot animate outside their parent's bounds
  5. Measuring Views • Problem: Views not measured until sometime after

    inflation • ViewTreeObserver - lets you know when a View has been measured • OnGlobalLayoutListener • OnPreDrawListener • Can cancel drawing before it happens
  6. ViewTreeObserver Pattern final View view = findViewById(R.id.view); view.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {

    public boolean onPreDraw() { view.getViewTreeObserver().removeOnPreDrawListener(this); // Measure here! return true; } });
  7. Measuring "After" • Align to other existing Views • Create

    invisible "dummy" Views to animate towards • Start in the correct position, animate towards it
  8. Running Animators • ObjectAnimator - animate! • AnimatorSet - synchronize

    multiple Animators • AnimatorListener - setup and cleanup • Canceling Animators w/ reverse()
  9. Property Animators • Generic animation framework • Animates any value

    over time • Not limited to just visual animations • Basic building block for most animations
  10. ObjectAnimator • Type of property animator • Used for animating

    essential View properties • Position (or translation) • Rotation • Scale • Alpha • Can be used on custom View properties
  11. ObjectAnimator // Uses built-in property to avoid reflection ObjectAnimator.ofFloat(myView, View.ALPHA,

    1).start(); // Alternative, with PropertyValuesHolder // Depends on setAlpha() and getAlpha() PropertyValuesHolder pvh = PropertyValuesHolder.ofFloat("alpha", 0, 1); ObjectAnimator.ofPropertyValuesHolder(mySecondView, pvh);
  12. AnimatorSet ObjectAnimator one = ObjectAnimator.ofFloat(view1, "alpha", 1); ObjectAnimator two =

    ObjectAnimator.ofFloat(view2, "alpha", 1); AnimatorSet set = new AnimatorSet(); set.playTogether(one, two); set.start();
  13. Animator Listeners ObjectAnimator anim = ObjectAnimator.ofFloat(view, "alpha", 1); anim.addListener(new AnimatorListenerAdapter()

    { public void onAnimationEnd(Animator animation) { // Clean-up code here } }); anim.start();
  14. Reversing Course • ValueAnimator.reverse() • Useful for smoothly canceling an

    animator • Can recursively traverse AnimatorSet for ValueAnimators
  15. Performance • Choppy animation == painful • Performance cannot be

    an afterthought • Smooth animations informs View structure
  16. Performance Breakdown • Layout - size/location of Views • Draw

    - what's inside Views • Render - pushing it on screen
  17. Render Performance • Initiated every time pixels are put on

    screen • Varies with pixel count/ speed of device • Try to reduce overdraw
  18. Profile GPU Rendering • Blue - Draw • Red -

    Process • Orange - Execute • Green line - your goal
  19. Show GPU Overdraw • Shows overdrawn pixels • Best to

    worst: nothing, blue, green, red, dark red • Some overdraw necessary, but reduce if possible
  20. Show Hardware Layer Updates • Flashes green on HW layer

    redraw • If constantly flashing, you're doing something wrong!
  21. Systrace • Measures everything on the system • Much more

    accurate than TraceView • Bigger picture view
  22. Profile Warning • Can be inaccurate • One profiling tool

    at a time, please • Profile multiple devices
  23. Layers • Layers store drawn Views for reuse • Reduces

    drawing during animation • Reduces overdraw during animation
  24. Layer Pattern final View myView = findViewById(R.id.my_view); myView.setLayerType(View.LAYER_TYPE_HARDWARE, null); myView.animate()

    .translationX(50) .setListener(new AnimatorListenerAdapter() { public void onAnimationEnd(Animator animation) { myView.setLayerType(View.LAYER_TYPE_NONE, null); } }) .start();
  25. Layer Caveats • Warning: redrawing a layer is *slower* than

    non-layer • DisplayLists will rebuild layers when necessary • Layering simple Views just hurts performance
  26. ImageView Blocking Layout public void setIsFixedSize(boolean isFixedSize) { mIsFixedSize =

    isFixedSize; } public void setImageBitmap(Bitmap bm) { mBlockMeasurement = true; super.setImageBitmap(bm); mBlockMeasurement = false; } public void requestLayout() { if (!mBlockMeasurement || !mIsFixedSize) { super.requestLayout(); } }
  27. Alpha Compositing • Needed for Views w/ multiple internal layers

    • Renders into offscreen buffer before fade • Slower, obviously
  28. hasOverlappingRendering() • New in API 16 • Off-screen rendering not

    required for all Views • Return false for any single-layer custom View
  29. ViewPropertyAnimator • Retrieved via View.animate() • Shortcut for simple animations

    • Better performance when manipulating multiple values of a View • Cons: no easy way to reverse • Cons: no way to group animations
  30. Tween Animations • The original, so backwards compatible • Sometimes

    necessary • Fragment transactions • Limited to simple property changes • Not as rich as property animators
  31. Interpolators • Controls the speed of the animation • Accelerating

    • Decelerating • Overshoot • Makes animations feel "right"
  32. SurfaceView vs. TextureView • TextureView is API 4.0+ • TextureView

    only works in HW accelerated windows • TextureView can, itself, be animated • SurfaceView uses hack and acts weird • TextureView is not as fast as SurfaceView
  33. Activity Window Animations • Custom tween animations between Activities •

    Limited to full-screen transitions • Activity.overridePendingTransition() • android:windowAnimationStyle
  34. Fragment Animations • Custom animations during Fragment transactions (adding/removing) •

    Limited to full-Fragment animations • Support library uses tween animations (instead of Animators)
  35. Fragment Animations • Fragment.onCreateAnimation() • Dynamic tweens • FragmentTransaction.setCustomAnimations() •

    Pre-built tweens • FragmentTransaction.setTransition() and setTransitionStyle() • Pre-defined animation styles
  36. Complex Fragment/ Activity Animations • Transition state • A -->

    A + B --> B • Invisible Fragments/transparent Activities • Single Activity, many Fragments/Views • ...Insert your solution here!
  37. set directions • View methods: setLeft(), setRight(), setTop(), setBottom() •

    Skip layout during animations • Parent layout blows away values, may have to block
  38. Drawable Animations • AnimationDrawable - frame animations • Custom animated

    Drawable in a View • Drawable.setCallback() • View.verifyDrawable()
  39. layoutAnimation • LayoutAnimation Controller • Staggers animations when Views are

    displayed • Useful for grid views • Useful for widget animations
  40. ViewOverlay • New in API 4.3 • Generically add Drawables

    connected to Views • Can render outside parent bounds
  41. TransitionManager • New in 4.4 • Transition automatically between two

    ViewGroups • Not fully backwards compatible (yet)
  42. Resources • Android: goo.gl/4aZIzM • DevBytes: goo.gl/QeTM9B • Chet Haase:

    graphics-geek.blogspot.com/ • Romain Guy: curious-creature.org • Google IO Sessions (esp. with Haase/Guy)
  43. Thank You! • Blog: http://daniel-codes.blogspot.com/ • Movies App Source: http://goo.gl/WiRTlQ

    • Twitter: @danlew42 • Plus: https://plus.google.com/+DanielLew/