<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by George Venios on Medium]]></title>
        <description><![CDATA[Stories by George Venios on Medium]]></description>
        <link>https://medium.com/@veniosg?source=rss-d4bb70158dd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wBk3WkYgjjqTEzDHe0Az7g.jpeg</url>
            <title>Stories by George Venios on Medium</title>
            <link>https://medium.com/@veniosg?source=rss-d4bb70158dd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:45:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@veniosg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Runtime theming of translucent Activities]]></title>
            <link>https://medium.com/pxhouse/runtime-theming-of-translucent-activities-640013ad40d0?source=rss-d4bb70158dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/640013ad40d0</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-styles]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[George Venios]]></dc:creator>
            <pubDate>Mon, 29 Jan 2018 09:31:01 GMT</pubDate>
            <atom:updated>2018-01-29T09:31:01.492Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The curious case of windowIsTranslucent</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfK0CIgQ5Rw_H3JXTJ3DjQ.jpeg" /></figure><p>Nowadays, it’s common to see apps allowing the user to change their look. A common way of implementing this is by passing the user’s theme of choice to <a href="https://developer.android.com/reference/android/app/Activity.html#setTheme(int)">setTheme()</a>. For most cases, you don’t need to set a theme for the Activity in the AndroidManifest as any operation involving it will happen after the setTheme() call.</p><p>But what if you need a themed activity to be translucent? Android seems to ignore the <a href="https://developer.android.com/reference/android/R.attr.html#windowIsTranslucent">windowIsTranlucent=true</a> flag on themes passed to <a href="https://developer.android.com/reference/android/app/Activity.html#setTheme(int)">setTheme()</a> and keeps our <a href="https://developer.android.com/reference/android/view/Window.html">Window</a> opaque. Trying to set a translucent Theme in AndroidManifest does retain the flag, but we can’t know which variant the user has picked at compile time and we’d lose the benefit of any custom styling and/or attributes.</p><h4>The solution</h4><p>The solution to retaining window translucency with custom styling comes by using a simple, if somewhat hidden, trick.</p><p>1. First, we need to set a translucent theme for the Activity on the manifest — @android:style/Theme.Translucent for example. Any translucent theme would suffice since we’ll be overwriting the in-memory copy that will be used for inflations.</p><p>2. Then, instead of directly setting our theme by calling <a href="https://developer.android.com/reference/android/app/Activity.html#setTheme(int)">setTheme(R.style.MyOwnTranslucentTheme)</a> (which will disable the translucency no matter the flag’s value), we need to update the Activity’s theme with the attributes and values of the actual theme we intended to use. Just call <a href="https://developer.android.com/reference/android/content/res/Resources.Theme.html#applyStyle(int,%20boolean)">getTheme().applyStyle(R.style.MyOwnTranslucentTheme, true)</a> to fill the copy of Theme.Translucent with the attributes from MyOwnTranslucentTheme.</p><p>That was it! You can now have the user select a theme and keep using it on your translucent Activities!</p><h4>One more thing…</h4><p>Worth noting is that this technique can’t be used to enable window translucency at runtime. Android seems to only enable it when it is set on the theme used in the AndroidManifest and there are no calls to setTheme() in the activity code. Trying to set the flag by using the applyStyle() trick bears pretty inconsistent results, as illustrated by this painstakingly crafted ASCII table:</p><pre>╔═══════════════════╦════════════════════╦═════════════════════════╗║ Initial/XML Theme ║  Overriding theme  ║         Result          ║<br>╠═══════════════════╬════════════════════╬═════════════════════════╣<br>║ True              ║ False              ║ Becomes opaque          ║<br>║ False             ║ True               ║ Remains opaque          ║<br>║ True              ║ True               ║ Remains translucent     ║<br>║ False             ║ False              ║ Remains opaque          ║<br>╚═══════════════════╩════════════════════╩═════════════════════════╝</pre><p><em>The first two columns are values of the windowIsTranslucent theme attribute defined on the respective themes.</em></p><blockquote>Want to see this trick used in production? <a href="https://play.google.com/store/apps/details?id=com.veniosg.dir">Check out Dir</a>, an open source file manager app for Android.</blockquote><blockquote>We’re always looking for contributors — visit the <a href="https://github.com/veniosg/Dir">project’s Github page</a> for more info!</blockquote><p><a href="https://play.google.com/store/apps/details?id=com.veniosg.dir">Dir - Open source material file manager - Android Apps on Google Play</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=640013ad40d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pxhouse/runtime-theming-of-translucent-activities-640013ad40d0">Runtime theming of translucent Activities</a> was originally published in <a href="https://medium.com/pxhouse">pxHouse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interactive animations made easy]]></title>
            <link>https://medium.com/@veniosg/interactive-animations-made-easy-5412942c164d?source=rss-d4bb70158dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5412942c164d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-animations]]></category>
            <category><![CDATA[shazam]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[George Venios]]></dc:creator>
            <pubDate>Thu, 21 Dec 2017 05:15:32 GMT</pubDate>
            <atom:updated>2017-12-21T05:15:32.126Z</atom:updated>
            <content:encoded><![CDATA[<p>How many times have you had to implement a simple animation that is controlled by some user interaction like scrolling?</p><p>It seems simple but come implementation time, you’re probably cracking out pen and paper, trying to figure out what the exact maths is. What’s worse, you end up with code that looks much more complex than what the animation might warrant.</p><h3>Enter map()</h3><p>The idea is that every time you implement an animation like that, what you’re implementing is a special case of this function:</p><pre>public static float map(float value, <br>   float iStart, float iEnd, <br>   float oStart, float oEnd) {<br>   if (iStart &gt; iEnd || oStart &gt; oEnd) {<br>      throw new IllegalArgumentException(“Range is inverted”);<br>   }</pre><pre><strong>   float unboundedMap = oStart + (oEnd — oStart) * ((value — iStart) / (iEnd — iStart));<br></strong>   return min(max(unboundedMap, oStart), oEnd);<br>}</pre><p>Sometimes your input might directly map to your output, in which case you’d do something simple like v.setAlpha(swipeOffset) and can omit map() altogether. But notice what happens when you want to fully show v when you’ve only swiped to 50%:</p><p>v.setAlpha(0.5f * swipeOffset)</p><p>And what if you only want to start fading in at 50% and be fully opaque at 70%?</p><pre>float rangeScaleFactor = (0.7f — 0.5f) / 1; <br>float scaledSwipeOffset = swipeOffset * rangeScaleFactor;<br>v.setAlpha(0.5f + max(0, min(1, scaledSwipeOffset)));</pre><p>Extracting constants might improve this but it is still a chore to read and understand. Additionally, how long would it take you to reach the above? Even worse, this solution hides the design’s intention and allows glitches to more easily creep their way into your UIs.</p><p>Enter map(in, inStart, inEnd, outStart, outEnd). What we actually did above is we implemented a simple mapping function that takes inputs in [0, 1] and maps them to [0.5, 0.7]. Using our original map() function we simply get:<br> v.setAlpha(map(swipeOffset, 0, 1, 0.5f, 0.7f))</p><p>Which is already much clearer but we can simplify it even further. Since, more often than not you just need to either map from a range of [0, 1] or to it, we can omit some arguments and get mapFromPercent(in, outStart, outEnd) mapToPercent(in, inStart, inEnd) [0], and our code becomes just</p><p>v.setAlpha(mapToPercent(swipeOffset, 0.5f, 0.7f))</p><p>Much closer to what the design intended and trivial to reason about and update. Happy days!</p><h3>The case for interpolators</h3><p>Another, less obvious use of mapToPercent() is that it allows us to easily use interpolators in interaction animations. Here’s a simple extension to our previous example that uses an AccelerateDecelerateInterpolator.</p><pre>Interpolator i = new AccelerateDecelerateInterpolator();<br><strong>float linearAlpha = mapToPercent(swipeOffset, 0.5f, 0.7f);<br>float interpolatedAlpha = i.getInterpolation(linearAlpha);</strong><br>v.setAlpha(interpolatedAlpha);</pre><p>Using interpolators this way can keep the UI feeling snappy and responsive but still respect animation best practices (like easing translations as the component reaches its resting positions) that make interfaces feel natural and polished.</p><h3>Examples</h3><p>An example of this technique in action can be found right in Shazam’s track page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*9kgnijvqZ60K4N4TRxcE1Q.gif" /><figcaption>Notice how the store bar reacts to scroll</figcaption></figure><p>And here is the code that controls the animations, in relation to an “expansion progress” property of the view, itself derived from the view’s position and the vertical space available to it. It uses all of the techniques mentioned above, including interpolating map()’s output.</p><pre><em>public class ExpandableActionsContainerView extends FrameLayout {<br>/** REST OF IMPLEMENTATION **/</em></pre><pre><em> /**<br>  * @param progress 0 means completely collapsed, 1 expanded.<br>  */<br> </em>public void setExpansionProgress(float progress) {<br>  if (expansionProgress != progress) {<br>   expansionProgress = progress;</pre><pre>   float collapseProgress = 1 - expansionProgress;<br>   float collapsedActionsAlpha = interpolator.getInterpolation(<strong><em>mapToPercent</em></strong>(collapseProgress, 0.33f, 1));<br>   float expandedActionsAlpha = <strong><em>mapToPercent</em></strong>(expansionProgress, 0.76f, 1);<br>   float headerTranslationY = <strong><em>mapFromPercent</em></strong>(collapsedActionsAlpha, expandedHeaderTranslationY, collapsedHeaderTranslationY);<br>   float translationZ = <strong><em>mapFromPercent</em></strong>(collapseProgress, 0, COLLAPSED_TRANSLATION_Z);<br>   int height = (int) <strong><em>mapFromPercent</em></strong>(expansionProgress, getMinimumHeight(), expandedHeight);</pre><pre>   collapsedActionsContainer.setAlpha(collapsedActionsAlpha);<br>   expandedActionsContainer.setAlpha(expandedActionsAlpha);<br>   headerContent.setTranslationY(headerTranslationY);<br>   this.setTranslationZ(translationZ);<br>   this.setEffectiveHeight(height);<br>  }<br> }<br>}</pre><p>For a more advanced example check out the post below to read how we cranked this technique to the max to create the Choreographer pattern — along with the full open source implementation of a demo app!</p><p><a href="https://blog.shazam.com/behind-the-scenes-of-the-shazam-animation-9bc7f922b2be">Behind the scenes of the Shazam animation</a></p><p>[0] For completeness, the implementations of mapFromPercent and mapToPercent:</p><pre>public static float <strong>mapFromPercent</strong>(float pc, float lBound, float uBound) {<br> return map(pc, 0, 1, lBound, uBound);<br>}</pre><pre>public static float <strong>mapToPercent</strong>(float value, float lBound, float uBound) {<br> return map(value, lBound, uBound, 0, 1);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5412942c164d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android widget adventures]]></title>
            <link>https://medium.com/pxhouse/advanced-collection-widgets-76c0dd6d408a?source=rss-d4bb70158dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c0dd6d408a</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-application]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-widget]]></category>
            <dc:creator><![CDATA[George Venios]]></dc:creator>
            <pubDate>Thu, 12 Oct 2017 10:01:00 GMT</pubDate>
            <atom:updated>2017-10-20T18:03:25.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*RSBr-J9eDYm2sMZ2xGxq4w.gif" /></figure><p>One of the main motivations for building <a href="https://play.google.com/store/apps/details?id=co.pxhouse.done"><strong>Done</strong></a> was to overcome some of the frustrations of the current top task management apps and craft the best mobile daily planner.</p><p>When trying to manage tasks, the tools you’re using should fade in the background. The standard to which I hold task management apps is the experience of using pen and paper: Adding, crossing out and seeing pending tasks should be this simple and intuitive.</p><p>While having a good in-app UI is desirable, task management apps benefit immensely from also having a functionally equivalent home screen widget. Therefore, the goal was for Done’s widget to behave the same way as the in-app UI, ensuring the transition between the in-app and widget experiences is seamless. They’re all part of the same app so it is only natural they would look and feel the same.</p><p>It was then clear that the items on the widget list need to be expandable. At first this looks impossible. Android offers no obvious way to make items in a ListView expandable, let alone allow doing it over RemoteViews.</p><p>Looking more closely to what similar apps have implemented suggests that some solution should be possible. For example, on list item clicks, Any.do’s widget draws the <em>Mark As Complete</em> action in place of the task item, so it seems that we can at the very least swap clicked item layouts. Also, as Todoist’s widget proves, it is possible to emulate more advanced functionality like <em>Contextual Actionbar</em> and multi-selection in our widgets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*DpSIbRGSETOaPIVPQY03rw.png" /><figcaption>Todoist’s widget with a selected item</figcaption></figure><p>Indeed, if we look at the problem from a different angle it becomes apparent that if we get our hands a bit dirty these behaviours are well within reach. What we’re really after is allowing clicks on an item to update said item’s view.</p><p>In-app this is trivial. When building the item layout in the adapter, all you need to do is attach a click listener, which on click lets the adapter know that it should toggle an item’s <em>selected</em> flag. The adapter then updates its internal selectedIds, and triggers an item update, which in turn causes onBindViewHolder() to be called, allowing us to draw the selected version of the item view. In Done’s case, we only allow a single item to be selected at a time, and selection means expansion. This happens by toggling the visibility of an actions_container view in the item’s layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLeCVeZ96c6YrQEvmfNYWA.png" /><figcaption>Selectable items in-app</figcaption></figure><p>RemoteViews on the other hand have no concept of a click listener. What they do have instead is the ability to fire a PendingIntent when a view is clicked. This works brilliantly when you just need to trigger an action, but what about when you need to update the state of the item instead?</p><p>The key to get to the solution is realising that we need to make our RemoteViewsFactory behave a bit more like an adapter: it should be able to hold (selection) state, and the items should be able to update it. Since the link between actions and adapter state is broken, we need to restore it some other way.</p><p>One way to update RemoteViewFactory’s selection state from external components is by delegating that logic to another class, and then use it as a collaborator in the factory itself. We’ll call this class WidgetSelectionStateStore. On a basic level, all this class does is keep the selected item id (per widget instance, if you’re feeling generous). Depending on your needs, it can either persist (database, shared preferences etc) or it can be a singleton with static fields. This way we can change a RemoteViewFactory’s state from any component, regardless of its ability to access the factory itself.</p><p>We can now wire our RemoteViews, their factory, the WidgetSelectionStateStore and the widget item’s click receiver to emulate the Adapter’s behaviour.</p><p>Clicking on an item fires a PendingIntent that launches a receiver, effectively replacing our click listener. Like the listener, the receiver is responsible for informing the WidgetSelectionStateStore that an item needs to be toggled and then requesting a widget update which will trigger the RemoteViewsFactory’s onDataUpdated() method and request new RemoteViews for all list items. Here, in our getViewAt() method we set the “actions container” visibility to either visible or gone based on the selection state returned by our (now updated) WidgetSelectionStateStore.</p><p>That was it, our collection widget now supports selectable items!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEm7IO1kQucZqfR7sHMXhg.png" /><figcaption>Selectable items in RemoteView lists</figcaption></figure><h3>Conclusion</h3><p>This pattern is not limited to enabling item expansion in list widgets but can be adapted to implement multi selection/checkable items, contextual actions and any other layout update based on item state and user interaction.</p><p>For Done it allowed keeping the interface consistent, providing a more intuitive user experience and getting us one more step towards our goal of effortless task planning.</p><p><strong>Done</strong> is a day-to-day task planner that aims to be the next best thing after post-it notes. <a href="https://play.google.com/store/apps/details?id=co.pxhouse.done">Get it here!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c0dd6d408a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pxhouse/advanced-collection-widgets-76c0dd6d408a">Android widget adventures</a> was originally published in <a href="https://medium.com/pxhouse">pxHouse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the scenes of the Shazam animation]]></title>
            <link>https://medium.com/@veniosg/behind-the-scenes-of-the-shazam-animation-9bc7f922b2be?source=rss-d4bb70158dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bc7f922b2be</guid>
            <category><![CDATA[android-animations]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[George Venios]]></dc:creator>
            <pubDate>Wed, 16 Aug 2017 10:19:17 GMT</pubDate>
            <atom:updated>2017-08-16T11:54:58.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zyJVsqwCt5zmqeydM0CStQ.png" /></figure><p>With Shazam’s latest redesign we had a chance to rethink the way our Listening animation is implemented.</p><p>Our goals for the redesign were smooth animations and seamless transitions for all components within the tagging flow, of which the big blue Shazam button is a major part.</p><p>To achieve these goals, we needed a robust but flexible architecture that would allow defining different state animations (Tagging, Idle etc) independently but would also support transitioning between them, even across Activities.</p><blockquote>All code snippets on this post are coming from an open source sample implementation of this architecture. <a href="https://github.com/shazam/choreographer-example/raw/master/ShazamChoreographerExample.apk">Download the APK</a> or view out <a href="https://github.com/shazam/choreographer-example">the code on Github</a>.</blockquote><p>Our solution consists of two core components: the Choreographer (<a href="https://developer.android.com/reference/android/view/Choreographer.html">not this one</a>), responsible for generating the relative values that define the look of each part of the button for each frame, and the Renderer, responsible for translating these values into concrete measurements and draw commands. These relative values are contained in a Frame object, which is a simple data class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*SWNl6evXDJkHav1Mong_VA.png" /></figure><h3>Renderer</h3><p>The Renderer is the most straightforward part of this system. It is implemented as an Android View that onDraw() gets a new Frame from a Choreographer, translates its values into real dimensions based on the space available, draws (in our case directly to the Canvas) and then calls invalidate() to schedule drawing the next frame. The code as implemented in <a href="https://github.com/shazam/choreographer-example/blob/master/app/src/main/java/com/shazam/choreographerexample/animation/choreographer/FunkyView.java">FunkyView</a>:</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>   <strong>// Read new frame</strong><br>   Frame f = choreographer.frameOn(uptimeMillis());</pre><pre>   <strong>// Translate to concrete values</strong><br>   float cx = getWidth() / 2;<br>   float cy = getHeight() / 2;<br>   int radius = (int) (buttonMaxWidth * f.scale) / 2;</pre><pre><strong>   // Draw<br></strong>   setTranslationY(f.translationY * maxTranslationY);<br>   buttonPaint.setColor(f.color);<br>   buttonPaint.setAlpha((int) (f.alpha * 255));<br>   canvas.drawCircle(cx, cy, radius, buttonPaint);</pre><pre><strong>   // Schedule<br></strong>   invalidate();<br>}</pre><p>Android caps the onDraw() callbacks to match 60fps, also taking VSync into account, so we don’t need to worry about manually scheduling invalidations. The Renderer is also responsible for drawing performance optimisations like reducing overdraw and potentially flattening its view hierarchy.</p><h3>Choreographer</h3><p>The Choreographer is the component doing the heavy lifting of tracking the different states, transitioning between them and doing the nitty gritty work of managing statically configured Animators, which in turn control the way each visible component behaves (e.g. moving circles and ripples, the logo etc).</p><blockquote>Check out <a href="https://github.com/shazam/choreographer-example/blob/master/app/src/main/java/com/shazam/choreographerexample/animation/choreographer/DullChoreographer.java">DullChoreographer</a> for a basic Choreographer implementation.</blockquote><p>To simplify things, we have one concrete Choreographer class per tagging state, giving us the benefit of self-contained animation logic and ease of modification if we need to independently change the behaviour of only a single state later. This also simplifies use of signals other than simple Animators to control the look of each component; for example the bass volume controls the size of the button when in the Listening state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*ZTVPme2Rl9BoRPQpiGcgzg.png" /></figure><p>But then, if the Choreographers know nothing about each other, how do we smoothly transition between them? The basic premise here is to create a <em>Choreographer cross-fader</em>, which takes the output Frames of two Choreographers and merges them in a single Frame. A full implementation of this concept is provided by <a href="https://github.com/shazam/choreographer-example/blob/master/app/src/main/java/com/shazam/choreographerexample/animation/choreographer/TransitioningChoreographer.java">TransitioningChoreographer</a>.</p><p>And what about transitions between screens? Surely, that’s not as easy as transitioning normal, static views like the framework’s <a href="https://developer.android.com/reference/android/transition/Transition.html">Transition</a> facilities allow. The principle is actually the same, in that the first frame of the new screen should pick up exactly where the last frame of the old one stopped. The additional catch in our case is that this includes the animation itself, because if for example a component is halfway faded out when the next Activity becomes visible, only retaining the current alpha value of 50% is not enough. If we are to have a seamless transition, the animation must not just start with the right next value but also keep moving at the same rate.</p><p>In more concrete terms, this means that after for example calling secondChoreographer.cloneFrom(originalChoreographer), both originalChoreographer and secondChoreographer must be producing a sequence of Frames containing the exact same values for the same timestamps.[0]</p><p>Before we move on with how we achieve this, we’ll need to talk about a special little class that makes our task much easier.</p><h3>LiteAnimator</h3><p>That class is <a href="https://github.com/shazam/choreographer-example/blob/master/app/src/main/java/com/shazam/choreographerexample/animation/LiteAnimator.java">LiteAnimator</a>, which is a custom-built, lightweight Animator, as the name obviously suggests. It is more flexible than Android’s equivalent and should have slightly less overhead because it is poll-only — no listeners needed or supported. To inform it about animation start we pass the start timestamp, allowing us to start animations in the present, but also in the past or future (which will make more sense in the next section).</p><p>LiteAnimator accepts standard Android Interpolators, start and end delays, supports seeking and supports only playing a certain part of the animation — which keeps the implementation close to the design to aid designer-developer communication and help with future updates. [1]</p><p>One of its most powerful features is that its output is independent of the wall clock at the time of querying and on animation start, meaning you can query it about the progress of the animation of any time. Because of this, Animators using the same configuration (interpolator, duration, startTime etc) will output the same value when queried about the same timestamp. This is very important as it means that to replicate instances we only need the original startTime, provided we have configured them in the same way.</p><h3>More Choreographer</h3><p>(In the next sections, whenever talking about Animators I’m actually referring to LiteAnimators)</p><p>We have already established that Choreographers are in effect Animator mixers, and that each of the Choreographer’s Animators are, by definition, configured the same way. Therefore, all we need to clone any Choreographer is its original startTime.</p><p>The keen reader may have noticed how, for this section, I have conveniently ignored microphone input. The reason is that microphone values will be the same across Choreographer instances since the microphone is, for all intents and purposes, a singleton.</p><p>As a side note, Android’s <a href="https://developer.android.com/reference/android/animation/ValueAnimator.html">ValueAnimator</a> supports seeking, which for most designs should be enough to allow seamlessly replacing Animator instances mid-animation.</p><h3>State Transitions</h3><p>On the technical side, transitioning between Choreographers works by getting the produced Frames from both Choreographers, assigning weights to them based on the transition progress and then combining them based on these weights to the actual resulting Frame. [2] The code from <a href="https://github.com/shazam/choreographer-example/blob/master/app/src/main/java/com/shazam/choreographerexample/animation/choreographer/TransitioningChoreographer.java">TransitioningChoreographer</a>:</p><pre>@Override<br>public Frame frameOn(long now) {<br>   <strong>// Get transition progress</strong><br>   float progress = transitionAnimator.getAnimatedFraction(now);<br>   Frame from = fromChoreographer.frameOn(now);<br>   Frame to = toChoreographer.frameOn(now);</pre><pre>   <strong>// Map transition progress to concrete values between &quot;from&quot; and &quot;to&quot; Frames</strong><br>   int red = (int) (mapFromPercent(progress, red(from.color), red(to.color)));<br>   int green = (int) (mapFromPercent(progress, green(from.color), green(to.color)));<br>   int blue = (int) (mapFromPercent(progress, blue(from.color), blue(to.color)));<br>   frame.color = Color.argb(255, red, green, blue);<br>   frame.scale = mapFromPercent(progress, from.scale, to.scale);<br>   frame.alpha = mapFromPercent(progress, from.alpha, to.alpha);<br>   frame.translationY = mapFromPercent(progress, from.translationY, to.translationY);</pre><pre><strong>   // Return blended frame</strong><br>   return frame;<br>}</pre><p>While not apparent from this snippet, this approach requires the two Frames to have the same number and kind of components, but since we’re moving between different states of the same button, we can assign reasonable defaults for any components missing from some of the states (e.g. the circles are only there when the app is Tagging).</p><p>What’s better is that since the transition itself is just an animation like any other, we can still use Interpolators to finely control the rate of the transition over time.</p><h3>Across states and Activities</h3><p>Combined with what we’ve established in the previous sections, this means that we can replicate the exact state of <em>transitioning</em> Choreographers by only keeping 3 values: the start times of the original and final Choreographers and the start time of the transition Animator. This means we’re able to seamlessly keep transitioning between states even while we’re moving to a new screen — all we need to do is pass 3 longs. In our sample project, this is represented as the <a href="https://github.com/shazam/choreographer-example/blob/1168d51ce4eb7722c4c0c6b39d90976cb06bce28/app/src/main/java/com/shazam/choreographerexample/animation/choreographer/TransitioningChoreographer.java#L126">TransitioningChoreographer.State</a> class.</p><p>Despite it being possible, in our final implementation we ended up not utilizing this feature as it is impossible to avoid dropping frames when creating a new Activity (which would have been clearly visible mid-animation). To avoid that, we defer the state transition until after the new Activity has launched. Luckily, the delay between the click event and animation start is small enough to avoid impacting perceived responsiveness. Transitions between Fragments should be free of this issue and should be able to jump between states with no regard for the changing containers.</p><p>In contrast, in the sample project, button presses kick off a transition to the FUNKY state and <a href="https://github.com/shazam/choreographer-example/blob/1168d51ce4eb7722c4c0c6b39d90976cb06bce28/app/src/main/java/com/shazam/choreographerexample/FirstActivity.java#L46">only launch the new activity halfway through it</a>, to fully demonstrate the capabilities of this approach.</p><h3>Conclusion</h3><p>There are many more details and decisions behind our final implementation to meet our goals of reducing the app size, maintaining animation performance and providing a top-notch user experience, but the overall architecture outlined in this article should give a good, general view of the system and will hopefully help others needing to implement similarly complex animations avoid some of the pitfalls and complexities we faced.</p><p>As always, <a href="https://play.google.com/store/apps/details?id=com.shazam.android">check out the animation</a> on your device, and post feedback and questions in the comments!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7p8MfOS14GU%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7p8MfOS14GU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7p8MfOS14GU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf3acd4ed1dd3face07c0406bf46bf5b/href">https://medium.com/media/bf3acd4ed1dd3face07c0406bf46bf5b/href</a></iframe><p>[0] The actual code involves passing the result of <a href="https://github.com/shazam/choreographer-example/blob/1168d51ce4eb7722c4c0c6b39d90976cb06bce28/app/src/main/java/com/shazam/choreographerexample/animation/choreographer/FunkyView.java#L68">FunkyView.freezeState()</a> to the next Activity and then calling the new FunkyView’s <a href="https://github.com/shazam/choreographer-example/blob/1168d51ce4eb7722c4c0c6b39d90976cb06bce28/app/src/main/java/com/shazam/choreographerexample/animation/choreographer/FunkyView.java#L72">unfreezeState()</a> with it as we’re not directly exposing Choreographers to Activities. Without that layer, it would actually look like this:</p><pre>newChoreographer.restoreFromState(oldChoreographer.getState());</pre><p>[1] In AfterEffects this is actually cropping a single run and then looping it indefinitely, but for our purposes doing this in realtime makes more sense as it fits better with the rest of the implementation.</p><p>[2] As an aside, you’d still have to follow this weighted average technique even if all that is different between your animators is their duration. By keeping your Animators across Choreographers and animating just their duration you would effectively be constantly changing the animation’s progress for the duration of the transition — potentially making the animation run in reverse.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bc7f922b2be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best practices for happy Android resources]]></title>
            <link>https://medium.com/@veniosg/best-practices-for-happy-android-resources-9445c1b521d6?source=rss-d4bb70158dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9445c1b521d6</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[android-xml]]></category>
            <category><![CDATA[android-styles]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-resources]]></category>
            <dc:creator><![CDATA[George Venios]]></dc:creator>
            <pubDate>Fri, 21 Jul 2017 13:45:30 GMT</pubDate>
            <atom:updated>2017-07-25T14:42:22.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_QKDInpQdqtb0cssJNOWg.png" /></figure><p>Architectural discussions for Android are all the rage but people seem to ignore the unsung hero that is the Android resource system. Treat it with love and it will fill your life with rainbows — ignore it and you’re in for a bunch of tech and design debt that’ll make your app sad, old and squeaky. This is a list of suggestions that will help keep that beast tamed and your codebase sparkling clean 🏆</p><h3>Themes and Styles</h3><ul><li>All styles should have a parent. This is to help with cases where you need to use a style in a theme attribute. Then you can safely use it as the default style for all widgets of a type in a Theme (e.g. ?android:textViewStyle) without losing the sane defaults Android provides.</li><li>Prefer inheriting from AppCompat instead of system styles to ensure backwards compatibility.</li><li>Do not create styles that are only used once.</li><li>Do not create styles for groups of attributes that just happen to be the same. (e.g. 16dp left padding).</li><li>Follow naming conventions of your style’s parent. By matching system/AppCompat names they’ll be easier to find (e.g. &lt;style name=”Widget.Shazam.Button” parent=”@style/Widget.AppCompat.Button”/&gt;)</li><li>&lt;opinion_alert&gt;Use implicit inheritance when possible. It’s slightly easier to navigate and forces you to name and structure styles better. &lt;/opinion_alert&gt;</li><li>Group widget styles based on the widget they’re designed for. Again, way easier to find.</li><li>Do not define layout_* attributes in styles. These are layout specific and should be duplicated for each layout even if they happen to be the same.</li><li>On that same point, using dimensions for duplicated layout_* attributes should be enough to ensure views behave the same without risking values being ignored because of the inflation method used.</li><li><a href="https://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources">Qualified resources</a> are your friend. Instead of defining multiple styles that have hardcoded dimensions/drawables and are switched based on configuration, only specify one style and define resource variables that point to a different resource for each configuration. This way your large style library is kept as concise (and navigable) as possible.</li></ul><h3>Text appearance</h3><ul><li>TextAppearance is not a normal Widget Style. TextAppearance only controls:</li></ul><ol><li>textColor, textColorHighlight, textColorHint, textColorLink</li><li>textSize</li><li>textStyle</li><li>textAllCaps</li><li>typeface</li><li>fontFamily</li><li>Shadow (shadowColor, shadowDx, shadowDy, shadowRadius)</li><li>elegantTextHeight</li><li>letterSpacing</li><li>fontFeatureSettings</li></ol><ul><li>Attributes set using style override ones set using textAppearance. Attributes set in the layout override everything.</li><li>Define a TextAppearance library (even if it’s only a direct subset of the ones provided by AppCompat) and only use that in your themes and layouts. This will make future app-wide and OS independent look &amp; feel updates a 2 minute change. For extra points define it in a separate file like styles_textappearance.xml and share it with your designers. They are sure to love you.</li><li>For even more points use themed resources for colours and string resources for your fonts. Don’t forget the .Inverse variants!</li><li>To ensure consistent-looking TextViews, do not define any of the TextAppearance attributes in a normal style, but always set a TextAppearance from your library on that style’s android:textAppearance field.</li></ul><h3>Colours</h3><ul><li>Keep naming consistent. Colours with transparency are named: &lt;solid_colour_name&gt;_XXpc, where XX is the alpha value expressed as a %. For example, black_60pc is #80000000.</li><li>Keeping colours grouped obviously helps too. A good way to group them is keeping the following separate as they tend to be large enough groups on their own: <em>greys</em>, <em>white variants</em>, <em>black variants</em>, <em>all brand palette colours</em>, and then <em>all references</em> to these, grouped by feature. This way the actual colour definitions will rarely be changed, and your layouts and styles needn’t be touched if they do. YMMV, so decide based on your colour list.</li><li>If trying to override a colour in another configuration, use refs.xml. An example of this could be switching the status bar colour based on API level from one grayscale value to another. colors.xml should not know about details like that, it’s only a library.</li><li>This colour list could also be shared with your design team so they don’t flood you with new colours for every new screen, and old screens are kept up to date, keeping both the app and your xml lean and consistent.</li></ul><h3>Attributes (attrs.xml)</h3><ul><li>Attribute names should use camelCase to keep consistent with the system.</li><li>If a system attribute fits your needs, use that instead of creating a new one. Examples are background, foreground, color etc. You can even include them in &lt;declare-styleable&gt; tags and layouts without re-defining them. Just use android: before the name — no need to specify format. This way everyone knows what values are expected and how the view will be affected.</li></ul><h3>Resources</h3><ul><li>Drawable names should look like: &lt;type&gt;_&lt;group&gt;_&lt;subgroup&gt;(_&lt;variant&gt;).xml</li><li>E.g. bg_button_primary.xml for a primary-color button background.</li><li>Common drawable prefixes: ic_ (icons), bg_ (backgrounds), div_ (dividers).</li><li>Same for layouts: activity_, fragment_, view_ and item_ are common prefixes.</li></ul><h3>General notes</h3><ul><li>Margin is a layout attribute and controls the space around the view the parent leaves empty. Padding is a view attribute and controls internal space left empty within the view. They are almost never interchangeable and if unsure, use margin. Margin should be used for positioning, whereas padding should be used for internal concerns of a View like touch feedback and increasing the clickable area.</li><li>For buttons, use styles instead of just backgrounds. This way, you should get more stuff for free (e.g. android:stateListAnimator) and therefore better UI and UX.</li><li>XML can get very unreadable very fast. As you would in Java, always try to group attributes/styles/themes together based on their type and look.</li></ul><p>Following these guidelines at Shazam has made creating polished and consistent layouts a breeze. Having structured our resources this way helped immensely in our redesign efforts, as neatly separated resources make finding, moving, modifying and deleting them much easier.</p><p>We’d love to hear your thoughts or tips you’re using in your own apps, so please share them in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9445c1b521d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing with MutableLiveData]]></title>
            <link>https://medium.com/pxhouse/unit-testing-with-mutablelivedata-22b3283a7819?source=rss-d4bb70158dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/22b3283a7819</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-lifecycle]]></category>
            <category><![CDATA[android-libraries]]></category>
            <category><![CDATA[android-testing]]></category>
            <category><![CDATA[component-lifecycle]]></category>
            <dc:creator><![CDATA[George Venios]]></dc:creator>
            <pubDate>Wed, 19 Jul 2017 08:01:00 GMT</pubDate>
            <atom:updated>2018-03-02T20:37:18.543Z</atom:updated>
            <content:encoded><![CDATA[<p>Building <a href="https://play.google.com/store/apps/details?id=co.pxhouse.done">Done</a>, I used <a href="https://developer.android.com/topic/libraries/architecture/index.html">Android Architecture Components</a>, <a href="https://developer.android.com/topic/libraries/data-binding/index.html">Data Binding</a> and <a href="https://developer.android.com/topic/libraries/architecture/room.html">Room</a>. Inevitably, while writing tests I found myself needing to assert on code that’s called inside a <a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html">LiveData</a> observer, in its onChanged() callback.</p><p>While easy, the fix wasn’t obvious, and even after Googling, the answer wasn’t readily available so I’m posting it here to help future users of LiveData.</p><h3>The problem</h3><p>Seeing how LiveData itself doesn’t provide a setValue() method, the first step is to create a <a href="https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData.html">MutableLiveData</a> object in your tests, pass it to your mock/fake LiveData provider (for example, if you’re using Room this is your mock <a href="https://developer.android.com/reference/android/arch/persistence/room/Dao.html">Dao</a>), and then continue happily asserting on calls made in onChanged().</p><p>Try that though and you’re greeted with this crash:</p><pre>java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See <a href="http://g.co/androidstudio/not-mocked">http://g.co/androidstudio/not-mocked</a> for details.</pre><pre>at android.os.Looper.getMainLooper(Looper.java)<br> at android.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:58)<br> at android.arch.core.executor.AppToolkitTaskExecutor.isMainThread(AppToolkitTaskExecutor.java:87)<br> at android.arch.lifecycle.LiveData.assertMainThread(LiveData.java:408)<br> at android.arch.lifecycle.LiveData.setValue(LiveData.java:290)<br> at android.arch.lifecycle.MutableLiveData.setValue(MutableLiveData.java:33)</pre><p>Which is descriptive enough but all it really says is that you are doomed if you’re trying to setValue() while running plain Java unit tests.</p><h3>The solution</h3><p>No need to fret as it turns out you can still use this method to test your LiveData observers!</p><ul><li>First, add this dependency in your module’s build.gradle file:</li></ul><pre>testImplementation &#39;android.arch.core:core-testing:1.0.0-alpha3&#39;</pre><p><em>Make sure you use the same version as the rest of your </em><em>android.arch.* dependencies!</em></p><ul><li>Then, in the test class where you need to call setValue() and assert, add this field:</li></ul><pre>@Rule</pre><pre>public TestRule rule = new InstantTaskExecutorRule();</pre><p>Behind the scenes, this bypasses the main thread check, and immediately runs any tasks on your test thread, allowing for immediate and predictable calls and therefore assertions.</p><p>I hope this helps more folks avoid getting stuck on this as it has been a major annoyance during my experiments with the otherwise straightforward Android Components library.</p><p>Download Done to see the resulting app!</p><p><a href="https://play.google.com/store/apps/details?id=co.pxhouse.done">Done - Daily planner, to do &amp; widget - Android Apps on Google Play</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22b3283a7819" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pxhouse/unit-testing-with-mutablelivedata-22b3283a7819">Unit testing with MutableLiveData</a> was originally published in <a href="https://medium.com/pxhouse">pxHouse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buttery smooth animations on a stacking RecyclerView]]></title>
            <link>https://medium.com/@veniosg/buttery-smooth-animations-on-a-stacking-recyclerview-17f6ef8df1c3?source=rss-d4bb70158dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f6ef8df1c3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[perfmatters]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[shazam]]></category>
            <dc:creator><![CDATA[George Venios]]></dc:creator>
            <pubDate>Wed, 12 Apr 2017 10:01:13 GMT</pubDate>
            <atom:updated>2017-07-05T14:36:37.432Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago Shazam launched Discover, which gives users a daily digest of content curated to their individual musical preferences. This is its journey to smoothness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*kPHtN9avk4JPZf0s9qfvsg.gif" /><figcaption><a href="https://www.youtube.com/watch?v=qkR6k-eLXKw">Click here for actual video</a> 🎬</figcaption></figure><p>The feed is implemented as a RecyclerView with a purpose-built LayoutManager that supports any <em>stacking </em>transformation by delegating the actual animations to the card views themselves. While there are many considerations for this specific implementation, the key insight is that we are translating Y-axis RecyclerView scroll inputs to per-card <em>stacking progress</em> deltas, basing the mapping on max allowed stacked items, current item height and screen height. [0]</p><h3>The problem</h3><p>The obvious problem with this design is that it introduces lots and lots of overdraw. A very rough estimate is that we’re drawing each pixel ~6 times (RecyclerView background + 3 stacked cards’ backgrounds + 3 stacked cards’ contents, which can even be full-bleed images). Another issue is that cards can have deep hierarchies making their inflation, measurement and layout costly. And to make matters worse, the LayoutManager has to create and add views as the items are moving, making framerate drops all the more noticeable. [1]</p><h3>The solution</h3><p>When optimising code always start with the changes that will have the greatest impact.</p><p>A good approach is to first verify things are actually running slow by using the <a href="https://developer.android.com/topic/performance/rendering/profile-gpu.html"><em>Profile GPU Rendering</em></a> developer option. Then, if they actually are, use <a href="https://developer.android.com/studio/profile/systrace.html"><em>SysTrace</em></a> to identify the cause of the slowdown. Its interface might look daunting at first but it’s a powerful aid on the road to performant apps. As always, remember that not all API levels and devices behave the same so make sure you test on a number of configurations.</p><p>Following the techniques described next, we were able to get a silky smooth scrolling experience.</p><h4>View Layers</h4><p>Views are only ever going to update once, when binding children to data [2]. Using layers will flatten the hierarchy to a single texture and obviously make drawing operations faster in exchange for memory. In the case of the digest cards, all scrolling transformations can be done natively on the GPU, so our item view textures will not update on every new frame (we’re only changing scaleXY, translationY and translationZ).</p><p>Be extra cautious when using hardware-backed layers because if used incorrectly they can destroy your performance as you could easily end up redrawing your View <em>and</em> re-uploading the texture to GPU on every single frame. A good rule of thumb is: never invalidate() and always check with the <em>Show hardware layer updates </em>developer option.</p><p>This remedies the internal overdraw caused by the cards’ contents and makes drawing faster as we no longer have to traverse the items’ subtrees or upload a myriad commands to GPU when drawing them.</p><h4>Manually clipping cards</h4><p>Even after utilising View layers we’re still on ~3x overdraw. By definition, our LayoutManager stacks views on top of each other with large chunks of them being invisible.</p><p>The good news is that we can completely eliminate card overdraw [3] by iterating from top to bottom child (top = last drawn), updating an <em>area-already-drawn</em> Rect and at the same time passing the non-overlapped area of each card’s visible Rect to its <a href="https://developer.android.com/reference/android/view/View.html#setClipBounds(android.graphics.Rect)">View.setClipBounds()</a>.</p><p>A caveat here is that the coordinates passed to setClipBounds() are pre-transformation so we have to take view scaling into account when updating the <em>area-already-drawn</em>, and then translate back to pre-transformation coordinates when passing to setClipBounds().</p><h4>Deferring image loading</h4><p>Large bitmap uploads to GPU are expensive and a bunch of our item layouts require large, full-bleed images. As our LayoutManager will create and try to bind data to new children mid-scroll [1], trying to immediately load images will drop a noticeable amount of frames at the worst time possible.</p><p>Delaying image loading until the RecyclerView is in <a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html#SCROLL_STATE_IDLE">SCROLL_STATE_IDLE</a> allows us to load the images at a time when dropping frames is much lower-impact as our views are no longer reacting to user interaction.</p><h4>Asynchronous layout inflations</h4><p>By this point, the scrolling performance was as good as one could get once you had scrolled through a few cards, but we were visibly dropping frames on the first few cards — arguably the most important part of the experience. The cause for this was card layout inflations.</p><p>We had already made a decision to go with XML in defining the card layouts due to readability, theming and the benefits of configuration-based resource resolving so migrating our definitions to Java wasn’t an option. The solution to this came in the form of the <a href="https://developer.android.com/reference/android/support/v4/view/AsyncLayoutInflater.html">AsyncLayoutInflater</a>. Migration is very easy — we only had to take care of waiting for the inflation to finish and then bind the data instead of doing it right away.</p><p>Since the inflation would take at most ~5 frames on our test devices, the maximum amount of time empty cards would be on-screen is less than 85ms, and since cards that are first appearing are roughly 90% obscured, this is a very low-impact issue.</p><h4>Final thoughts</h4><p>After introducing these changes, the cards no longer lagged behind the user’s finger making for a much more fluid and natural interaction which in turn gives the whole experience a more polished feel.</p><p>Every implementation is different so these techniques may or may be worth the effort for everyone so remember to not jump the gun trying to squeeze out these precious few extra milliseconds. You know what they say about premature optimisation. 👹</p><p><a href="https://play.google.com/store/apps/details?id=com.shazam.android">Don’t forget to install the app</a>, play with the feed and let us know what you think!</p><p>[0] For help with implementing a LayoutManager the <a href="http://wiresareobsolete.com/2014/09/building-a-recyclerview-layoutmanager-part-1/"><em>Building a RecyclerView LayoutManager</em></a> blog series from Dave Smith is invaluable.</p><p>[1] This is because we don’t want cards at the bottom of the stack to visibly pop in/out of view and therefore the best time to add and remove children is when a moving card completely overlaps the space between the <em>peeking</em> bottom card and the card at the top of the stack. This can either happen when the user drags or when the stack snaps — either way, things will be moving and framerate is important.</p><p>[2] The backing surfaces will actually update again when images are loaded but that’s indirectly handled by deferring image loading.</p><p>[3] We still have ~1x overdraw on the whole layout but clipping the background (a solid colour) at roughly the union of all card’s visible Rects is not worth the effort. Additionally, elevation shadows introduce some overdraw but I trust Android to optimise that one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f6ef8df1c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>