15

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?
SimonVT
  • 1,080
  • 10
  • 12

1 Answers1

13

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.

Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • 1
    Okay, I might have celebrated a little early. I accidentally left it at HARDWARE. I can see it create the layer after onSizeChanged(), taking the usual 70+ms. However, the same thing happens the first time i switch to HARDWARE when I need to animate it. – SimonVT Sep 04 '12 at 23:29
  • 1
    Just to be clear, I'm getting the large delay twice. Once when i buildLayer() from onSizeChanged(), and once the first time I animate the view. After that, there is no delay. – SimonVT Sep 05 '12 at 17:00