SurfaceView

public class SurfaceView
extends View

java.lang.Object
   ↳ android.view.View
     ↳ android.view.SurfaceView


Provides a dedicated drawing surface embedded inside of a view hierarchy. You can control the format of this surface and, if you like, its size; the SurfaceView takes care of placing the surface at the correct location on the screen

The surface is Z ordered so that it is behind the window holding its SurfaceView; the SurfaceView punches a hole in its window to allow its surface to be displayed. The view hierarchy will take care of correctly compositing with the Surface any siblings of the SurfaceView that would normally appear on top of it. This can be used to place overlays such as buttons on top of the Surface, though note however that it can have an impact on performance since a full alpha-blended composite will be performed each time the Surface changes.

The transparent region that makes the surface visible is based on the layout positions in the view hierarchy. If the post-layout transform properties are used to draw a sibling view on top of the SurfaceView, the view may not be properly composited with the surface.

Access to the underlying surface is provided via the SurfaceHolder interface, which can be retrieved by calling getHolder().

The Surface will be created for you while the SurfaceView's window is visible; you should implement SurfaceHolder.Callback#surfaceCreated and SurfaceHolder.Callback#surfaceDestroyed to discover when the Surface is created and destroyed as the window is shown and hidden.

One of the purposes of this class is to provide a surface in which a secondary thread can render into the screen. If you are going to use it this way, you need to be aware of some threading semantics:

Note: Starting in platform version Build.VERSION_CODES.N, SurfaceView's window position is updated synchronously with other View rendering. This means that translating and scaling a SurfaceView on screen will not cause rendering artifacts. Such artifacts may occur on previous versions of the platform when its window is positioned asynchronously.

Note: Starting in platform version Build.VERSION_CODES.UPSIDE_DOWN_CAKE, SurfaceView will support arbitrary alpha blending. Prior platform versions ignored alpha values on the SurfaceView if they were between 0 and 1. If the SurfaceView is configured with Z-above, then the alpha is applied directly to the Surface. If the SurfaceView is configured with Z-below, then the alpha is applied to the hole punch directly. Note that when using Z-below, overlapping SurfaceViews may not blend properly as a consequence of not applying alpha to the surface content directly.

Summary

Inherited XML attributes

Constants

int SURFACE_LIFECYCLE_DEFAULT

Default lifecycle of the Surface owned by this SurfaceView.

int SURFACE_LIFECYCLE_FOLLOWS_ATTACHMENT

The Surface lifecycle is tied to SurfaceView attachment.

int SURFACE_LIFECYCLE_FOLLOWS_VISIBILITY

The Surface lifecycle is tied to SurfaceView visibility.

Inherited constants

Inherited fields

Public constructors

SurfaceView(Context context)
SurfaceView(Context context, AttributeSet attrs)
SurfaceView(Context context, AttributeSet attrs, int defStyleAttr)
SurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Public methods

void applyTransactionToFrame(SurfaceControl.Transaction transaction)

Adds a transaction that would be applied synchronously with displaying the SurfaceView's next frame.

void draw(Canvas canvas)

Manually render this view (and all of its children) to the given Canvas.

boolean gatherTransparentRegion(Region region)

This is used by the ViewRoot to perform an optimization when the view hierarchy contains one or several SurfaceView.

SurfaceHolder getHolder()

Return the SurfaceHolder providing access and control over this SurfaceView's underlying surface.

IBinder getHostToken()

A token used for constructing SurfaceControlViewHost.

int getImportantForAccessibility()

Gets the mode for determining whether this View is important for accessibility.

SurfaceControl getSurfaceControl()

Return a SurfaceControl which can be used for parenting Surfaces to this SurfaceView.

boolean hasOverlappingRendering()

Returns whether this View has content which overlaps.

void setAlpha(float alpha)

Sets the opacity of the view to a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque.

void setChildSurfacePackage(SurfaceControlViewHost.SurfacePackage p)

Display the view-hierarchy embedded within a SurfaceControlViewHost.SurfacePackage within this SurfaceView.

void setClipBounds(Rect clipBounds)

Sets a rectangular area on this view to which the view will be clipped when it is drawn.

void setSecure(boolean isSecure)

Control whether the surface view's content should be treated as secure, preventing it from appearing in screenshots or from being viewed on non-secure displays.

void setSurfaceLifecycle(int lifecycleStrategy)

Controls the lifecycle of the Surface owned by this SurfaceView.

void setVisibility(int visibility)

Set the visibility state of this view.

void setZOrderMediaOverlay(boolean isMediaOverlay)

Control whether the surface view's surface is placed on top of another regular surface view in the window (but still behind the window itself).

void setZOrderOnTop(boolean onTop)

Control whether the surface view's surface is placed on top of its window.

Protected methods

void dispatchDraw(Canvas canvas)

Called by draw to draw the child views.

void onAttachedToWindow()

This is called when the view is attached to a window.

void onDetachedFromWindow()

This is called when the view is detached from a window.

void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect)

Called by the view system when the focus state of this view changes.

void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

boolean onSetAlpha(int alpha)

Invoked if there is a Transform that involves alpha.

void onWindowVisibilityChanged(int visibility)

Called when the window containing has change its visibility (between GONE, INVISIBLE, and VISIBLE).

Inherited methods

Constants

SURFACE_LIFECYCLE_DEFAULT

Added in API level 34
public static final int SURFACE_LIFECYCLE_DEFAULT

Default lifecycle of the Surface owned by this SurfaceView. The default lifecycle matches SURFACE_LIFECYCLE_FOLLOWS_VISIBILITY.

Constant Value: 0 (0x00000000)

SURFACE_LIFECYCLE_FOLLOWS_ATTACHMENT

Added in API level 34
public static final int SURFACE_LIFECYCLE_FOLLOWS_ATTACHMENT

The Surface lifecycle is tied to SurfaceView attachment. The Surface is created when the SurfaceView first becomes attached, but is not destroyed until this SurfaceView has been detached from the current window.

Constant Value: 2 (0x00000002)

SURFACE_LIFECYCLE_FOLLOWS_VISIBILITY

Added in API level 34
public static final int SURFACE_LIFECYCLE_FOLLOWS_VISIBILITY

The Surface lifecycle is tied to SurfaceView visibility. The Surface is created when the SurfaceView becomes visible, and is destroyed when the SurfaceView is no longer visible.

Constant Value: 1 (0x00000001)

Public constructors

SurfaceView

Added in API level 1
public SurfaceView (Context context)

Parameters
context Context

SurfaceView

Added in API level 1
public SurfaceView (Context context, 
                AttributeSet attrs)

Parameters
context Context

attrs AttributeSet

SurfaceView

Added in API level 1
public SurfaceView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

SurfaceView

Added in API level 1
public SurfaceView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr, 
                int defStyleRes)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

defStyleRes int

Public methods

applyTransactionToFrame

Added in API level 34
public void applyTransactionToFrame (SurfaceControl.Transaction transaction)

Adds a transaction that would be applied synchronously with displaying the SurfaceView's next frame. Note that the exact frame that the transaction is applied with is only well-defined when SurfaceView rendering is paused prior to calling applyTransactionToFrame(), so that the transaction is applied with the next frame rendered after applyTransactionToFrame() is called. If frames are continuously rendering to the SurfaceView when applyTransactionToFrame() is called, then it is undefined which frame the transaction is applied with. It is also possible for the transaction to not be applied if no new frames are rendered to the SurfaceView after this is called.

Parameters
transaction SurfaceControl.Transaction: The transaction to apply. The system takes ownership of the transaction and promises to eventually apply the transaction. This value cannot be null.

Throws
IllegalStateException if the underlying Surface does not exist (and therefore there is no next frame).

draw

Added in API level 1
public void draw (Canvas canvas)

Manually render this view (and all of its children) to the given Canvas. The view must have already done a full layout before this function is called. When implementing a view, implement onDraw(android.graphics.Canvas) instead of overriding this method. If you do need to override this method, call the superclass version.
If you override this method you must call through to the superclass implementation.

Parameters
canvas Canvas: The Canvas to which the View is rendered. This value cannot be null.

gatherTransparentRegion

Added in API level 1
public boolean gatherTransparentRegion (Region region)

This is used by the ViewRoot to perform an optimization when the view hierarchy contains one or several SurfaceView. SurfaceView is always considered transparent, but its children are not, therefore all View objects remove themselves from the global transparent region (passed as a parameter to this function).

Parameters
region Region: The transparent region for this ViewAncestor (window). This value may be null.

Returns
boolean Returns true if the effective visibility of the view at this point is opaque, regardless of the transparent region; returns false if it is possible for underlying windows to be seen behind the view.

getHolder

Added in API level 1
public SurfaceHolder getHolder ()

Return the SurfaceHolder providing access and control over this SurfaceView's underlying surface.

Returns
SurfaceHolder SurfaceHolder The holder of the surface.

getHostToken

Added in API level 30
public IBinder getHostToken ()

A token used for constructing SurfaceControlViewHost. This token should be passed from the host process to the client process.

Returns
IBinder The token This value may be null.

getImportantForAccessibility

Added in API level 16
public int getImportantForAccessibility ()

Gets the mode for determining whether this View is important for accessibility. A view is important for accessibility if it fires accessibility events and if it is reported to accessibility services that query the screen.

Returns
int The mode for determining whether a view is important for accessibility, one of IMPORTANT_FOR_ACCESSIBILITY_AUTO, IMPORTANT_FOR_ACCESSIBILITY_YES, IMPORTANT_FOR_ACCESSIBILITY_NO, or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS.

getSurfaceControl

Added in API level 29
public SurfaceControl getSurfaceControl ()

Return a SurfaceControl which can be used for parenting Surfaces to this SurfaceView. Note that this SurfaceControl is effectively read-only. Its only well-defined usage is in using the SurfaceControl as a parent for an application's hierarchy of SurfaceControls. All other properties of the SurfaceControl, such as its position, may be mutated by the SurfaceView at any time which will override what the application is requesting. Do not apply any SurfaceControl.Transaction to this SurfaceControl except for reparenting child SurfaceControls. See: SurfaceControl.Transaction#reparent.

Returns
SurfaceControl The SurfaceControl for this SurfaceView.

hasOverlappingRendering

Added in API level 16
public boolean hasOverlappingRendering ()

Returns whether this View has content which overlaps.

This function, intended to be overridden by specific View types, is an optimization when alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer and then composited into place, which can be expensive. If the view has no overlapping rendering, the view can draw each primitive with the appropriate alpha value directly. An example of overlapping rendering is a TextView with a background image, such as a Button. An example of non-overlapping rendering is a TextView with no background, or an ImageView with only the foreground image. The default implementation returns true; subclasses should override if they have cases which can be optimized.

Note: The return value of this method is ignored if forceHasOverlappingRendering(boolean) has been called on this view.

Returns
boolean true if the content in this view might overlap, false otherwise.

setAlpha

Added in API level 11
public void setAlpha (float alpha)

Sets the opacity of the view to a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque.

Note: setting alpha to a translucent value (0 < alpha < 1) can have significant performance implications, especially for large views. It is best to use the alpha property sparingly and transiently, as in the case of fading animations.

For a view with a frequently changing alpha, such as during a fading animation, it is strongly recommended for performance reasons to either override hasOverlappingRendering() to return false if appropriate, or setting a layer type on the view for the duration of the animation. On versions Build.VERSION_CODES.M and below, the default path for rendering an unlayered View with alpha could add multiple milliseconds of rendering cost, even for simple or small views. Starting with Build.VERSION_CODES.M, LAYER_TYPE_HARDWARE is automatically applied to the view at the rendering level.

If this view overrides onSetAlpha(int) to return true, then this view is responsible for applying the opacity itself.

On versions Build.VERSION_CODES.LOLLIPOP_MR1 and below, note that if the view is backed by a layer and is associated with a layer paint, setting an alpha value less than 1.0 will supersede the alpha of the layer paint.

Starting with Build.VERSION_CODES.M, setting a translucent alpha value will clip a View to its bounds, unless the View returns false from hasOverlappingRendering().

Parameters
alpha float: The opacity of the view. Value is between 0.0 and 1.0 inclusive

setChildSurfacePackage

Added in API level 30
public void setChildSurfacePackage (SurfaceControlViewHost.SurfacePackage p)

Display the view-hierarchy embedded within a SurfaceControlViewHost.SurfacePackage within this SurfaceView. This can be called independently of the SurfaceView lifetime callbacks. SurfaceView will internally manage reparenting the package to our Surface as it is created and destroyed. If this SurfaceView is above its host Surface (see setZOrderOnTop(boolean) then the embedded Surface hierarchy will be able to receive input. This will take ownership of the SurfaceControl contained inside the SurfacePackage and free the caller of the obligation to call SurfaceControlViewHost.SurfacePackage#release. However, note that SurfaceControlViewHost.SurfacePackage#release and SurfaceControlViewHost#release are not the same. While the ownership of this particular SurfaceControlViewHost.SurfacePackage will be taken by the SurfaceView the underlying SurfaceControlViewHost remains managed by it's original remote-owner.

Parameters
p SurfaceControlViewHost.SurfacePackage: The SurfacePackage to embed. This value cannot be null.

setClipBounds

Added in API level 18
public void setClipBounds (Rect clipBounds)

Sets a rectangular area on this view to which the view will be clipped when it is drawn. Setting the value to null will remove the clip bounds and the view will draw normally, using its full bounds.

Parameters
clipBounds Rect: The rectangular area, in the local coordinates of this view, to which future drawing operations will be clipped.

setSecure

Added in API level 17
public void setSecure (boolean isSecure)

Control whether the surface view's content should be treated as secure, preventing it from appearing in screenshots or from being viewed on non-secure displays.

Note that this must be set before the surface view's containing window is attached to the window manager.

See Display.FLAG_SECURE for details.

Parameters
isSecure boolean: True if the surface view is secure.

setSurfaceLifecycle

Added in API level 34
public void setSurfaceLifecycle (int lifecycleStrategy)

Controls the lifecycle of the Surface owned by this SurfaceView.

By default, the lifecycycle strategy employed by the SurfaceView is SURFACE_LIFECYCLE_DEFAULT.

Parameters
lifecycleStrategy int: The strategy for the lifecycle of the Surface owned by this SurfaceView. Value is SURFACE_LIFECYCLE_DEFAULT, SURFACE_LIFECYCLE_FOLLOWS_VISIBILITY, or SURFACE_LIFECYCLE_FOLLOWS_ATTACHMENT

setVisibility

Added in API level 1
public void setVisibility (int visibility)

Set the visibility state of this view.

Parameters
visibility int: One of View.VISIBLE, View.INVISIBLE, or View.GONE. Value is View.VISIBLE, View.INVISIBLE, or View.GONE

setZOrderMediaOverlay

Added in API level 5
public void setZOrderMediaOverlay (boolean isMediaOverlay)

Control whether the surface view's surface is placed on top of another regular surface view in the window (but still behind the window itself). This is typically used to place overlays on top of an underlying media surface view.

Note that this must be set before the surface view's containing window is attached to the window manager.

Calling this overrides any previous call to setZOrderOnTop(boolean).

Parameters
isMediaOverlay boolean

setZOrderOnTop

Added in API level 5
public void setZOrderOnTop (boolean onTop)

Control whether the surface view's surface is placed on top of its window. Normally it is placed behind the window, to allow it to (for the most part) appear to composite with the views in the hierarchy. By setting this, you cause it to be placed above the window. This means that none of the contents of the window this SurfaceView is in will be visible on top of its surface.

Note that this must be set before the surface view's containing window is attached to the window manager. If you target Build.VERSION_CODES#R the Z ordering can be changed dynamically if the backing surface is created, otherwise it would be applied at surface construction time.

Calling this overrides any previous call to setZOrderMediaOverlay(boolean).

Parameters
onTop boolean: Whether to show the surface on top of this view's window.

Protected methods

dispatchDraw

Added in API level 1
protected void dispatchDraw (Canvas canvas)

Called by draw to draw the child views. This may be overridden by derived classes to gain control just before its children are drawn (but after its own view has been drawn).

Parameters
canvas Canvas: the canvas on which to draw the view This value cannot be null.

onAttachedToWindow

Added in API level 1
protected void onAttachedToWindow ()

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before onDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).
If you override this method you must call through to the superclass implementation.

onDetachedFromWindow

Added in API level 1
protected void onDetachedFromWindow ()

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
If you override this method you must call through to the superclass implementation.

onFocusChanged

Added in API level 1
protected void onFocusChanged (boolean gainFocus, 
                int direction, 
                Rect previouslyFocusedRect)

Called by the view system when the focus state of this view changes. When the focus change event is caused by directional navigation, direction and previouslyFocusedRect provide insight into where the focus is coming from. When overriding, be sure to call up through to the super class so that the standard focus handling will occur.
If you override this method you must call through to the superclass implementation.

Parameters
gainFocus boolean: True if the View has focus; false otherwise.

direction int: Value is View.FOCUS_BACKWARD, View.FOCUS_FORWARD, View.FOCUS_LEFT, View.FOCUS_UP, View.FOCUS_RIGHT, or View.FOCUS_DOWN

previouslyFocusedRect Rect: This value may be null.

onMeasure

Added in API level 1
protected void onMeasure (int widthMeasureSpec, 
                int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overridden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpec int: horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

heightMeasureSpec int: vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

onSetAlpha

Added in API level 1
protected boolean onSetAlpha (int alpha)

Invoked if there is a Transform that involves alpha. Subclass that can draw themselves with the specified alpha should return true, and then respect that alpha when their onDraw() is called. If this returns false then the view may be redirected to draw into an offscreen buffer to fulfill the request, which will look fine, but may be slower than if the subclass handles it internally. The default implementation returns false.

Parameters
alpha int: The alpha (0..255) to apply to the view's drawing

Returns
boolean true if the view can draw with the specified alpha.

onWindowVisibilityChanged

Added in API level 1
protected void onWindowVisibilityChanged (int visibility)

Called when the window containing has change its visibility (between GONE, INVISIBLE, and VISIBLE). Note that this tells you whether or not your window is being made visible to the window manager; this does not tell you whether or not your window is obscured by other windows on the screen, even if it is itself visible.

Parameters
visibility int: The new visibility of the window. Value is View.VISIBLE, View.INVISIBLE, or View.GONE