Added in API level 14

TextureView


open class TextureView : View
kotlin.Any
   ↳ android.view.View
   ↳ android.view.TextureView

A TextureView can be used to display a content stream, such as that coming from a camera preview, a video, or an OpenGL scene. The content stream can come from the application's process as well as a remote process.

TextureView can only be used in a hardware accelerated window. When rendered in software, TextureView will draw nothing.

TextureView vs. SurfaceView Capabilities

  TextureView SurfaceView
Supports View alpha X U+
Supports rotations X  
Supports clipping X  
HDR support Limited (on Android T+) Full
Renders DRM content   X

Unlike SurfaceView, TextureView does not create a separate window but behaves as a regular View. This key difference allows a TextureView to have translucency, arbitrary rotations, and complex clipping. For example, you can make a TextureView semi-translucent by calling myView.setAlpha(0.5f).

One implication of this integration of TextureView into the view hierarchy is that it may have slower performance than SurfaceView. TextureView contents must be copied, internally, from the underlying surface into the view displaying those contents. For that reason, SurfaceView is recommended as a more general solution to problems requiring rendering to surfaces.

Using a TextureView is simple: all you need to do is get its SurfaceTexture. The SurfaceTexture can then be used to render content. The following example demonstrates how to render a video into a TextureView:

public class MyActivity extends Activity implements TextureView.SurfaceTextureListener {
       private MediaPlayer mMediaPlayer;
       private TextureView mTextureView;
 
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
 
           mMediaPlayer = new MediaPlayer();
 
           mTextureView = new TextureView(this);
           mTextureView.setSurfaceTextureListener(this);
           setContentView(mTextureView);
       }
 
       public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surfaceTexture,
                                             int width, int height) {
           AssetFileDescriptor fileDescriptor = // get file descriptor
           mMediaPlayer.setDataSource(fileDescriptor);
           mMediaPlayer.setSurface(new Surface(surfaceTexture));
           mMediaPlayer.prepareAsync();
           mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
               @Override
               public void onPrepared(MediaPlayer mp) {
                   mMediaPlayer.start();
               }
           });
          } catch (IOException e) {
              e.printStackTrace();
          }
       }
 
      @Override
      public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surfaceTexture,
                                              int width, int height) {
          // Handle size change depending on media needs
      }
 
      @Override
      public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surfaceTexture) {
          // Release unneeded resources
          mMediaPlayer.stop();
          mMediaPlayer.release();
          return true;
      }
 
      @Override
      public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surfaceTexture) {
           // Invoked every time there's a new video frame
      }
 
   }
  

Similarly, TextureView can supply the surface needed for GL rendering or camera previews. Camera2 APIs require the surface created by TextureView, although developers are recommended to use the CameraX APIs instead, for which PreviewView creates its own TextureView or SurfaceView internally.

A TextureView's SurfaceTexture can be obtained either by invoking getSurfaceTexture() or by using a SurfaceTextureListener. It is important to know that a SurfaceTexture is available only after the TextureView is attached to a window (and onAttachedToWindow() has been invoked.) It is therefore highly recommended you use a listener to be notified when the SurfaceTexture becomes available.

It is important to note that only one producer can use the TextureView. For instance, if you use a TextureView to display the camera preview, you cannot use lockCanvas() to draw onto the TextureView at the same time.

Summary

Nested classes
abstract

This listener can be used to be notified when the surface texture associated with this texture view is available.

Inherited XML attributes
Inherited constants
Public constructors
TextureView(context: Context)

Creates a new TextureView.

TextureView(context: Context, attrs: AttributeSet?)

Creates a new TextureView.

TextureView(context: Context, attrs: AttributeSet?, defStyleAttr: Int)

Creates a new TextureView.

TextureView(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int)

Creates a new TextureView.

Public methods
open Unit

Calling this method has no effect.

Unit
draw(canvas: Canvas)

Subclasses of TextureView cannot do their own rendering with the Canvas object.

open Bitmap?

Returns a android.graphics.Bitmap representation of the content of the associated surface texture.

open Bitmap?
getBitmap(width: Int, height: Int)

Returns a android.graphics.Bitmap representation of the content of the associated surface texture.

open Bitmap
getBitmap(bitmap: Bitmap)

Copies the content of this view's surface texture into the specified bitmap.

open Int

Always returns LAYER_TYPE_HARDWARE.

open SurfaceTexture?

Returns the SurfaceTexture used by this view.

open TextureView.SurfaceTextureListener?

Returns the SurfaceTextureListener currently associated with this texture view.

open Matrix
getTransform(transform: Matrix?)

Returns the transform associated with this texture view.

open Boolean

Returns true if the SurfaceTexture associated with this TextureView is available for rendering.

open Boolean

Indicates whether this View is opaque.

open Canvas?

Start editing the pixels in the surface.

open Canvas?
lockCanvas(dirty: Rect?)

Just like lockCanvas() but allows specification of a dirty rectangle.

open Unit

open Unit
setForeground(foreground: Drawable!)

open Unit

Updates the Paint object used with the current layer (used only if the current layer type is not set to LAYER_TYPE_NONE).

open Unit
setLayerType(layerType: Int, paint: Paint?)

The layer type of a TextureView is ignored since a TextureView is always considered to act as a hardware layer.

open Unit
setOpaque(opaque: Boolean)

Indicates whether the content of this TextureView is opaque.

open Unit

Set the SurfaceTexture for this view to use.

open Unit

Sets the SurfaceTextureListener used to listen to surface texture events.

open Unit
setTransform(transform: Matrix?)

Sets the transform to associate with this texture view.

open Unit

Finish editing pixels in the surface.

Protected methods
open Unit

Unit
onDraw(canvas: Canvas)

Subclasses of TextureView cannot do their own rendering with the Canvas object.

open Unit
onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int)

open Unit
onVisibilityChanged(changedView: View, visibility: Int)

Inherited functions
Inherited properties

Public constructors

TextureView

Added in API level 14
TextureView(context: Context)

Creates a new TextureView.

Parameters
context Context: The context to associate this view with. This value cannot be null.

TextureView

Added in API level 14
TextureView(
    context: Context,
    attrs: AttributeSet?)

Creates a new TextureView.

Parameters
context Context: The context to associate this view with. This value cannot be null.
attrs AttributeSet?: The attributes of the XML tag that is inflating the view. This value may be null.

TextureView

Added in API level 14
TextureView(
    context: Context,
    attrs: AttributeSet?,
    defStyleAttr: Int)

Creates a new TextureView.

Parameters
context Context: The context to associate this view with. This value cannot be null.
attrs AttributeSet?: The attributes of the XML tag that is inflating the view. This value may be null.
defStyleAttr Int: An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

TextureView

Added in API level 21
TextureView(
    context: Context,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int)

Creates a new TextureView.

Parameters
context Context: The context to associate this view with. This value cannot be null.
attrs AttributeSet?: The attributes of the XML tag that is inflating the view. This value may be null.
defStyleAttr Int: An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.
defStyleRes Int: A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.

Public methods

buildLayer

Added in API level 14
open fun buildLayer(): Unit

Calling this method has no effect.

Exceptions
java.lang.IllegalStateException If this view is not attached to a window

draw

Added in API level 14
fun draw(canvas: Canvas): Unit

Subclasses of TextureView cannot do their own rendering with the Canvas object.

Parameters
canvas Canvas: The Canvas to which the View is rendered.

getBitmap

Added in API level 14
open fun getBitmap(): Bitmap?

Returns a android.graphics.Bitmap representation of the content of the associated surface texture. If the surface texture is not available, this method returns null.

The bitmap returned by this method uses the Bitmap.Config#ARGB_8888 pixel format and its dimensions are the same as this view's.

Do not invoke this method from a drawing method (onDraw(android.graphics.Canvas) for instance).

If an error occurs during the copy, an empty bitmap will be returned.

Return
Bitmap? A valid Bitmap.Config#ARGB_8888 bitmap, or null if the surface texture is not available or the width <= 0 or the height <= 0

getBitmap

Added in API level 14
open fun getBitmap(
    width: Int,
    height: Int
): Bitmap?

Returns a android.graphics.Bitmap representation of the content of the associated surface texture. If the surface texture is not available, this method returns null.

The bitmap returned by this method uses the Bitmap.Config#ARGB_8888 pixel format.

Do not invoke this method from a drawing method (onDraw(android.graphics.Canvas) for instance).

If an error occurs during the copy, an empty bitmap will be returned.

Parameters
width Int: The width of the bitmap to create
height Int: The height of the bitmap to create
Return
Bitmap? A valid Bitmap.Config#ARGB_8888 bitmap, or null if the surface texture is not available or width is <= 0 or height is <= 0

getBitmap

Added in API level 14
open fun getBitmap(bitmap: Bitmap): Bitmap

Copies the content of this view's surface texture into the specified bitmap. If the surface texture is not available, the copy is not executed. The content of the surface texture will be scaled to fit exactly inside the specified bitmap.

Do not invoke this method from a drawing method (onDraw(android.graphics.Canvas) for instance).

If an error occurs, the bitmap is left unchanged.

Parameters
bitmap Bitmap: The bitmap to copy the content of the surface texture into, cannot be null, all configurations are supported
Return
Bitmap The bitmap specified as a parameter This value cannot be null.
Exceptions
java.lang.IllegalStateException if the hardware rendering context cannot be acquired to capture the bitmap

getSurfaceTexture

Added in API level 14
open fun getSurfaceTexture(): SurfaceTexture?

Returns the SurfaceTexture used by this view. This method may return null if the view is not attached to a window or if the surface texture has not been initialized yet.

See Also

getSurfaceTextureListener

Added in API level 14
open fun getSurfaceTextureListener(): TextureView.SurfaceTextureListener?

Returns the SurfaceTextureListener currently associated with this texture view.

Return
TextureView.SurfaceTextureListener? This value may be null.

getTransform

Added in API level 14
open fun getTransform(transform: Matrix?): Matrix

Returns the transform associated with this texture view.

Parameters
transform Matrix?: The Matrix in which to copy the current transform. Can be null.
Return
Matrix The specified matrix if not null or a new Matrix instance otherwise.

isAvailable

Added in API level 14
open fun isAvailable(): Boolean

Returns true if the SurfaceTexture associated with this TextureView is available for rendering. When this method returns true, getSurfaceTexture() returns a valid surface texture.

isOpaque

Added in API level 14
open fun isOpaque(): Boolean

Indicates whether this View is opaque. An opaque View guarantees that it will draw all the pixels overlapping its bounds using a fully opaque color. Subclasses of View should override this method whenever possible to indicate whether an instance is opaque. Opaque Views are treated in a special way by the View hierarchy, possibly allowing it to perform optimizations during invalidate/draw passes.

Return
Boolean True if this View is guaranteed to be fully opaque, false otherwise.

lockCanvas

Added in API level 14
open fun lockCanvas(): Canvas?

Start editing the pixels in the surface. The returned Canvas can be used to draw into the surface's bitmap. A null is returned if the surface has not been created or otherwise cannot be edited. You will usually need to implement SurfaceTextureListener#onSurfaceTextureAvailable(android.graphics.SurfaceTexture, int, int) to find out when the Surface is available for use.

The content of the Surface is never preserved between unlockCanvas() and lockCanvas(), for this reason, every pixel within the Surface area must be written. The only exception to this rule is when a dirty rectangle is specified, in which case, non-dirty pixels will be preserved.

This method can only be used if the underlying surface is not already owned by another producer. For instance, if the TextureView is being used to render the camera's preview you cannot invoke this method.

Return
Canvas? A Canvas used to draw into the surface, or null if the surface cannot be locked for drawing (see isAvailable()).

lockCanvas

Added in API level 14
open fun lockCanvas(dirty: Rect?): Canvas?

Just like lockCanvas() but allows specification of a dirty rectangle. Every pixel within that rectangle must be written; however pixels outside the dirty rectangle will be preserved by the next call to lockCanvas(). This method can return null if the underlying surface texture is not available (see isAvailable() or if the surface texture is already connected to an image producer (for instance: the camera, OpenGL, a media player, etc.)

Parameters
dirty Rect?: Area of the surface that will be modified. If null the area of the entire surface is used.
Return
Canvas? A Canvas used to draw into the surface, or null if the surface cannot be locked for drawing (see isAvailable()).

setBackgroundDrawable

Added in API level 14
open fun setBackgroundDrawable(background: Drawable!): Unit

setForeground

Added in API level 23
open fun setForeground(foreground: Drawable!): Unit
Parameters
foreground Drawable!: the Drawable to be drawn on top of the children

setLayerPaint

Added in API level 17
open fun setLayerPaint(paint: Paint?): Unit

Updates the Paint object used with the current layer (used only if the current layer type is not set to LAYER_TYPE_NONE). Changed properties of the Paint provided to setLayerType(int,android.graphics.Paint) will be used the next time the View is redrawn, but setLayerPaint(android.graphics.Paint) must be called to ensure that the view gets redrawn immediately.

A layer is associated with an optional android.graphics.Paint instance that controls how the layer is composed on screen. The following properties of the paint are taken into account when composing the layer:

If this view has an alpha value set to < 1.0 by calling setAlpha(float), the alpha value of the layer's paint is superseded by this view's alpha value.

Parameters
paint Paint?: This value may be null.

setLayerType

Added in API level 14
open fun setLayerType(
    layerType: Int,
    paint: Paint?
): Unit

The layer type of a TextureView is ignored since a TextureView is always considered to act as a hardware layer. The optional paint supplied to this method will however be taken into account when rendering the content of this TextureView.

Parameters
layerType Int: The type of layer to use with this view, must be one of LAYER_TYPE_NONE, LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE
paint Paint?: The paint used to compose the layer. This argument is optional and can be null. It is ignored when the layer type is LAYER_TYPE_NONE

setOpaque

Added in API level 14
open fun setOpaque(opaque: Boolean): Unit

Indicates whether the content of this TextureView is opaque. The content is assumed to be opaque by default.

Parameters
opaque Boolean: True if the content of this TextureView is opaque, false otherwise

setSurfaceTexture

Added in API level 16
open fun setSurfaceTexture(surfaceTexture: SurfaceTexture): Unit

Set the SurfaceTexture for this view to use. If a SurfaceTexture is already being used by this view, it is immediately released and not usable any more. The android.view.TextureView.SurfaceTextureListener#onSurfaceTextureDestroyed callback is not called for the previous SurfaceTexture. Similarly, the android.view.TextureView.SurfaceTextureListener#onSurfaceTextureAvailable callback is not called for the SurfaceTexture passed to setSurfaceTexture. The SurfaceTexture object must be detached from all OpenGL ES contexts prior to calling this method.

Parameters
surfaceTexture SurfaceTexture: The SurfaceTexture that the view should use. This value cannot be null.

setSurfaceTextureListener

Added in API level 14
open fun setSurfaceTextureListener(listener: TextureView.SurfaceTextureListener?): Unit

Sets the SurfaceTextureListener used to listen to surface texture events.

Parameters
listener TextureView.SurfaceTextureListener?: This value may be null.

setTransform

Added in API level 14
open fun setTransform(transform: Matrix?): Unit

Sets the transform to associate with this texture view. The specified transform applies to the underlying surface texture and does not affect the size or position of the view itself, only of its content.

Some transforms might prevent the content from drawing all the pixels contained within this view's bounds. In such situations, make sure this texture view is not marked opaque.

Parameters
transform Matrix?: The transform to apply to the content of this view. If null the transform will be set to identity.

unlockCanvasAndPost

Added in API level 14
open fun unlockCanvasAndPost(canvas: Canvas): Unit

Finish editing pixels in the surface. After this call, the surface's current pixels will be shown on the screen, but its content is lost, in particular there is no guarantee that the content of the Surface will remain unchanged when lockCanvas() is called again.

Parameters
canvas Canvas: The Canvas previously returned by lockCanvas() This value cannot be null.

Protected methods

onAttachedToWindow

Added in API level 14
protected open fun onAttachedToWindow(): Unit

onDraw

Added in API level 14
protected fun onDraw(canvas: Canvas): Unit

Subclasses of TextureView cannot do their own rendering with the Canvas object.

Parameters
canvas Canvas: The Canvas to which the View is rendered.

onSizeChanged

Added in API level 14
protected open fun onSizeChanged(
    w: Int,
    h: Int,
    oldw: Int,
    oldh: Int
): Unit
Parameters
w Int: Current width of this view.
h Int: Current height of this view.
oldw Int: Old width of this view.
oldh Int: Old height of this view.

onVisibilityChanged

Added in API level 14
protected open fun onVisibilityChanged(
    changedView: View,
    visibility: Int
): Unit
Parameters
changedView View: The view whose visibility changed. May be this or an ancestor view. This value cannot be null.
visibility Int: The new visibility, one of VISIBLE, INVISIBLE or GONE. Value is android.view.View#VISIBLE, android.view.View#INVISIBLE, or android.view.View#GONE