Android view animation and hardware layers - android

I'm currently trying to work out how to properly use hardware layers when animating views.
I'm implementing a ViewGroup that enables the user to drag a child view, after which I animate it to a position when they release (like how ViewPager will settle on a page). This article states that you should only enable hardware layers for the duration of the animation.
The issue I'm having is that after hardware layers are enabled Android has to create the layers, which takes 70-100ms on a Galaxy Nexus. This means I can't do it immediately before starting the animation, as having the delay between the drag and the animation would be very noticeable. I also can't enable it when starting a drag for the same reason.
Now, this delay is only present the first time hardware layers are created, so ideally I would want them to be created as soon as the views are added to the layout. I've been pointed to View.buildLayer(), but I'm unsure how to approach this.
What would be the correct way to achieve this?
Are there any methods in my ViewGroup I can override and call buildLayer() on the child views?
Can the hardware layer be invalidated in some way, causing another 70-100ms delay? And how do I handle this?

The delay happens when there's no layer in the cache, you should not see this delay for subsequent calls to setLayerType(NONE)/setLayerType(HARDWARE). You could call buildLayer() from onSizeChanged() to force a layer to be built and then put in the cache (call setLayerType(NONE) to move the layer to the cache.)
Note that the delay you are seeing depends greatly on the device you are running on.
The reason why you shouldn't keep layers enabled is that it doubles the amount of drawing work every time the view update. For instance, if you move a ListView into a layer and then scroll the list, each frame update during the scroll animation will cause: (a) the list to repaint into the layer (b) the layer to be drawn on screen. It's extremely wasteful and may cause performance issues depending on the complexity of your UI.

Related

How to translate a group of views efficiently?

I have a base layout that holds several views. I need to translate them along the x axis. Basically there are 2 types of translations happening the one that follows the finger all the way and the one that stops after certain threshold which gives a nice parallax-like effect.
So is it better to put the group of views that share same translation logic inside another container and translate the container or translate each view individually?
I know this might sound weird but Google always recommends to use flat view hierarchy because nested layouts are expensive to redraw, so does it mean that keeping just one layer of nesting and translating each view by hand is better?
Also this translation is applied to all the views in the RecyclerView, not just one.
I think you should keep a flat layout as Google recommends, and translate each view individually. I would create a custom view were you can set a threshold. And once set, you can simply pass the x position of the finger to them all, and they'll decide if they should move or not.
How to implement it requires more input or requirements before giving any suggestion. Besides performance problem, code maintainable should be considered too.
Base on my experience. With high-end phone and high API level (about >= 21), they have better hardware, effective way to manage memory and background task. The problem expensive to redraw you mentioned seems not too important with some simple animation. In this situation, code maintainability has higher priority, I will decide to have an extra FrameLayout container, wrap the View which have the same animation because you have less code => less logic. 0 or 2 FrameLayout have no noticeable difference in performance in this case
About low-end devices, if you want to target lower API users, performance becomes a top priority. Now both cases you mentioned have the effect on performance, one requires more memory to store more View and one requires more CPU to run animation. It's time for a trade-off. In your case when you have 2 translate animations run on any item in RecyclerView, I prefer to create 2 separate animations run on 2 View. This way I can save a bunch of extra containers => save memory, the animation is not run for all of the items so it only affects the CPU for a small amount of time during animation.
So to sum up, You have a different approach for each case, choose a top-priority for the case you choose, improve it, sacrifice the others that have less effect on the overall problem. No solution is 100% perfect, trade-off situation always happens when coding

Is it too much to call invalidate on every touch under certain condition

When an image is being dragged using touch over another custom view, I am setting the background color of the custom view from green to red. Off course I am listening to the onTouchEvents and I am comparing the coordinates of the dragged view to the custom view to see if there is a collision. Once collision is determined, I set the color and call invalidate on the view.
So invalidate is being called on every touch (when there is a collision). Is this frown upon? I feel the device heating up when this happens so not sure if this is normal when it comes to games
Thanks
View#nvalidate() indicates that a View needs to be redrawn and signals a draw pass. You can call this 50 times in a row, and it will only signal one draw pass. The draw pass will happen as soon as the system regains control on the main thread (or perhaps a little later depending on any other background operations that take control).
If you are animating something as you are with this custom View, then you are calling many draw passes to begin with so you may not even need to call View#invalidate() and simply just wait for the screen to redraw.
In fact, you can look at the source code and see that invalidate() is being called at the end of setBackground() to begin with. It's actually pretty rare to need to call it when you're changing properties of a View that the View itself is in control of. It's only needed if there are drawing operations that you're doing in addition to what the View itself is doing.

scrollingCache?

Can anybody explain the meaning of scrolling cache in Android. I stumbled upon this word, but was unable to find the explanation, either on android official website or on the web.
All I could find was how can I turn it on/off.
Thanks.
Scrolling cache is basically a drawing cache.
In android, you can ask a View to store its drawing in a cache called drawing cache (basically a bitmap). By default, a drawing cache is disabled because it takes up memory but you can ask the View to explicitly to create one either via setDrawingCacheEnabled or through hardware layers (setLayerType).
So why is it useful? Because using a drawing cache make your animation smooth compared to redrawing the view at every frame.
This type of animation can also be hardware accelerated because the rendering system can take this bitmap and upload it to the GPU as a texture (if using hardware layers) and do fast matrix manipulations on it (like change alpha, translate, rotation). Compare that to doing animation were you are redrawing (onDraw gets called) on every frame.
In the case of a listview, when you scroll by flinging, you are in essence animating the views of your list (either moving them up or down). The listview uses the drawing cache of its visible children (and some potentially visible children near the edges) to animate them very quickly.
Is there a disadvantage to using drawing cache? Yes it consumes memory which is why by default it is turned off for in a View. In the case of ListView, the cache automatically created for you as soon as you touch the ListView and move a little (to differentiate a tap from scroll). In other words, as soon as ListView thinks you are about to scroll/fling it will create a scroll cache for you to animate the scroll/fling motion.
scrollingCache is explained in full detail in the lecture of "the world of listView".
It's basically caches the scrolling itself so that it will move a bitmap, but according to my experience, it actually makes things much slower and take memory for nothing special.
scrollingCache is enabled by default, at least for listView . That's why if performance is important for you, you should consider disabling it.
I think you are talking about the following:
Imagine a list of 50 items where only 10 items are visible. Android will cache the next and previous (estimate) 5 items in a list item.
When you start scrolling through the list it will reuse the invisible item views, using the ArrayAdapter's function getView()
For example if you are scrolling to the top it will take a view on the bottom and place it on top with new data.
So scrolling cache are the next and previous items above/under the visible items.
official explanation: http://developer.android.com/reference/android/widget/AbsListView.html#attr_android:scrollingCache
Romain Guy's blog about the cache color hint optimization: http://www.curious-creature.org/2008/12/22/why-is-my-list-black-an-android-optimization/

Performance: How to prevent requestLayout() from laying out entire hierarchy

I have a pretty complex android-application. Already flattened view-hierarchies as far as possible, but I still have lags in the application. For example there is a menu with entries that collapse/expand by having their height set by a ValueAnimator. Typically the animation runs with a bit of a lag the first time, and smooth after this first pass.
I noticed that when i call "requestLayout()" on the Menu-Item, Android seems to do a layout-pass and multiple measure-passes through the entire hierarchy.
Since i know that although the Menu-Item(View) changes height, the Menu(View) itself doesn't, is there some way to tell this to the application?
Can i somehow perform this first pass that seems to lag myself so that it occurs after application start-up and not at the first touch-input?
Here's a sketch of the animation I'm doing:
I am not sure why a layout is being triggered in your animation but I am going to answer your question abstractly.
If you are calling requestLayout (either directly or indirectly) in your animation you are doing it WRONG.
requestLayout, for correctness and safety, does a full view traversal on the view hierarchy b/c conceptually changing bounding box of a node in the view hierarchy can result in change in the bounds of any other node. Not always the case but in general it could, thats why requestLayout is a full traversal.
All of this is just another way of saying requestLayout will eat away time from your 16.6 ms frame time slot and make your animation choppy. This is especially bad for deep and complex hierarchies with many RelativeLayouts which internally does two passes per level (thus potentially causing exponential passes on a subtree)
Now, if you want to animate change in dimension use setScale in a hardware layer. And at the end of the animation merrily call requestlayout and also destroy the layer (to free up memory).
Because its a layer, repeatedly calling setScale in your animation results in change of the texture on the GPU and as a result totally bypass the traversal mechanism of the view hierarchy. This should make it buttery smooth.
Your question looks like mine: Only relayout children and not all the tree
First, you can try to avoid complex view hierarchy for your view. If possible, explode views on views that doesn't depend on another one.
When an animation is performed, avoid any layout request. Start your animation with a delay if a layout request is pending.
Use hardware layers for animation if possible (maybe Android use it by default with ValueAnimator)

Difference between SurfaceView and View?

When is it necessary, or better to use a SurfaceView instead of a View?
Views are all drawn on the same GUI thread which is also used for all user interaction.
So if you need to update GUI rapidly or if the rendering takes too much time and affects user experience then use SurfaceView.
A few things I've noted:
SurfaceViews contain a nice rendering mechanism that allows threads to update the surface's content without using a handler (good for animation).
Surfaceviews cannot be transparent, they can only appear behind other elements in the view hierarchy.
I've found that they are much faster for animation than rendering onto a View.
For more information (and a great usage example) refer to the LunarLander project in the SDK
's examples section.
updated 05/09/2014
OK. We have official document now. It talked all I have mentioned, in a better way.
Read more detailed here.
Yes, the main difference is surfaceView can be updated on the background thread. However, there are more you might care.
surfaceView has dedicate surface buffer while all the view shares one surface buffer that is allocated by ViewRoot. In another word, surfaceView cost more resources.
surfaceView cannot be hardware accelerated (as of JB4.2) while 95% operations on normal View are HW accelerated using openGL ES.
More work should be done to create your customized surfaceView. You need to listener to the surfaceCreated/Destroy Event, create an render thread, more importantly, synchronized the render thread and main thread. However, to customize the View, all you need to do is override onDraw method.
The timing to update is different. Normal view update mechanism is constraint or controlled by the framework:You call view.invalidate in the UI thread or view.postInvalid in other thread to indicate to the framework that the view should be updated. However, the view won't be updated immediately but wait until next VSYNC event arrived. The easy approach to understand VSYNC is to consider it is as a timer that fire up every 16ms for a 60fps screen. In Android, all the normal view update (and display actually but I won't talk it today), is synchronized with VSYNC to achieve better smoothness. Now,back to the surfaceView, you can render it anytime as you wish. However, I can hardly tell if it is an advantage, since the display is also synchronized with VSYNC, as stated previously.
The main difference is that SurfaceView can be drawn on by background theads but Views can't.
SurfaceViews use more resources though so you don't want to use them unless you have to.
A SurfaceView is a custom view in Android that can be used to drawn inside it.
The main difference between a View and a SurfaceView is that a View is drawn in the
UI Thread, which is used for all the user interaction.
If you want to update the UI rapidly enough and render a good amount of information in
it, a SurfaceView is a better choice.
But there are a few technical insides to the SurfaceView:
1. They are not hardware accelerated.
2. Normal views are rendered when you call the methods invalidate or postInvalidate(), but this does not mean the view will be
immediately updated (A VSYNC will be sent, and the OS decides when
it gets updated. The SurfaceView can be immediately updated.
3. A SurfaceView has an allocated surface buffer, so it is more costly
One of the main differences between surfaceview and view is that to refresh the screen for a normal view we have to call invalidate method from the same thread where the view is defined. But even if we call invalidate, the refreshing does not happen immediately. It occurs only after the next arrival of the VSYNC signal. VSYNC signal is a kernel generated signal which happens every 16.6 ms or this is also known as 60 frame per second. So if we want more control over the refreshing of the screen (for example for very fast moving animation), we should not use normal view class.
On the other hand in case of surfaceview, we can refresh the screen as fast as we want and we can do it from a background thread. So refreshing of the surfaceview really does not depend upon VSYNC, and this is very useful if we want to do high speed animation. I have few training videos and example application which explain all these things nicely. Please have a look at the following training videos.
https://youtu.be/kRqsoApOr9U
https://youtu.be/Ji84HJ85FIQ
https://youtu.be/U8igPoyrUf8
Why use SurfaceView and not the classic View class...
One main reason is that SurfaceView can rapidly render the screen.
In simple words a SV is more capable of managing the timing and render animations.
To have a better understanding what is a SurfaceView we must compare it with the View class.
What is the difference... check this simple explanation in the video
https://m.youtube.com/watch?feature=youtu.be&v=eltlqsHSG30
Well with the View we have one major problem....the timing of rendering animations.
Normally the onDraw() is called from the Android run-time system.
So, when Android run-time system calls onDraw() then the application cant control
the timing of display, and this is important for animation. We have a gap of timing
between the application (our game) and the Android run-time system.
The SV it can call the onDraw() by a dedicated Thread.
Thus: the application controls the timing. So we can display the next bitmap image of the animation.

Categories

Resources