PreviewView


public final class PreviewView extends FrameLayout


Custom View that displays the camera feed for CameraX's Preview use case.

This class manages the preview Surface's lifecycle. It internally uses either a TextureView or SurfaceView to display the camera feed, and applies required transformations on them to correctly display the preview, this involves correcting their aspect ratio, scale and rotation.

If PreviewView uses a SurfaceView to display the preview stream, be careful when overlapping a View that's initially not visible (either INVISIBLE or GONE) on top of it. When the SurfaceView is attached to the display window, it calls requestTransparentRegion which requests a computation of the transparent regions on the display. At this point, the View isn't visible, causing the overlapped region between the SurfaceView and the View to be considered transparent. Later if the View becomes visible, it will not be displayed on top of SurfaceView. A way around this is to call requestTransparentRegion right after making the View visible, or initially hiding the View by setting its opacity to 0, then setting it to 1.0F to show it.

There are some limitations of transition animations to SurfaceView and TextureView, which applies to PreviewView as well.

See also

Summary

Nested types

The implementation mode of a PreviewView.

Options for scaling the preview vis-à-vis its container PreviewView.

Definitions for the preview stream state.

Public constructors

@UiThread
PreviewView(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)
@UiThread
PreviewView(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr,
    int defStyleRes
)

Public methods

@Nullable Bitmap

Returns a Bitmap representation of the content displayed on the PreviewView, or null if the camera preview hasn't started yet.

@Nullable CameraController

Get the CameraController.

@NonNull PreviewView.ImplementationMode

Returns the ImplementationMode.

@NonNull MeteringPointFactory

Gets the MeteringPointFactory for the camera currently connected to the PreviewView, if any.

@Nullable OutputTransform

Gets the OutputTransform associated with the PreviewView.

@NonNull LiveData<PreviewView.StreamState>

Gets a LiveData for the preview StreamState.

@NonNull PreviewView.ScaleType

Returns the ScaleType currently applied to the preview.

@Nullable ImageCapture.ScreenFlash

Returns an ImageCapture.ScreenFlash implementation based on the Window instance set via setScreenFlashWindow.

@Nullable Matrix

Gets the transformation matrix from camera sensor to PreviewView.

@NonNull Preview.SurfaceProvider

Gets a Preview.SurfaceProvider to be used with setSurfaceProvider.

@Nullable ViewPort

Gets a ViewPort based on the current status of PreviewView.

@Nullable ViewPort
@UiThread
getViewPort(int targetRotation)

Gets a ViewPort with custom target rotation.

boolean
boolean
void

Sets the CameraController.

void

Sets the ImplementationMode for the PreviewView.

void

Applies a ScaleType to the preview.

void

Sets the color of the top overlay view during screen flash.

void

Sets a Window instance for subsequent photo capture requests with FLASH_MODE_SCREEN set.

Protected methods

void
void

Inherited Constants

From android.view.View
static final int
static final int
static final int
static final int
static final int
static final int
static final Property<ViewFloat>
static final int
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE = "creditCardExpirationDate"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH = "creditCardExpirationMonth"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR = "creditCardExpirationYear"
static final String
static final String
AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode"
static final String
static final String
static final String
static final String
static final String
static final String
static final String
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int[]
static final int[]
static final int[]
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int
GONE = 8
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
KEEP_SCREEN_ON = 67108864
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
NO_ID = -1
static final int
static final int
static final int
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int[]
static final int[]
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final String
VIEW_LOG_TAG = "View"
static final int
static final int[]
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
From android.view.ViewGroup
static final int
static final int
static final int
static final int
static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

Inherited methods

From android.widget.FrameLayout
boolean
FrameLayout.LayoutParams
FrameLayout.LayoutParams
CharSequence
boolean

This method is deprecated.

boolean
void
onLayout(boolean changed, int left, int top, int right, int bottom)
void
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
void
setForegroundGravity(int foregroundGravity)
void
setMeasureAllChildren(boolean measureAll)
boolean
From android.view.View
void
void
void
ViewPropertyAnimator
void
void
boolean
void
void

This method is deprecated.

void
boolean
boolean
boolean
boolean
boolean
canScrollHorizontally(int direction)
boolean
canScrollVertically(int direction)
final void
void
final void
boolean
void
void
static int
combineMeasuredStates(int curState, int newState)
int
int
int
void
WindowInsets
int
int
int
AccessibilityNodeInfo
void
void

This method is deprecated.

boolean
boolean
dispatchNestedFling(float velocityX, float velocityY, boolean consumed)
boolean
dispatchNestedPreFling(float velocityX, float velocityY)
boolean
dispatchNestedPrePerformAccessibilityAction(
    int action,
    Bundle arguments
)
boolean
dispatchNestedPreScroll(
    int dx,
    int dy,
    int[] consumed,
    int[] offsetInWindow
)
boolean
dispatchNestedScroll(
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed,
    int[] offsetInWindow
)
boolean
void
draw(Canvas canvas)
void
drawableHotspotChanged(float x, float y)
final OnBackInvokedDispatcher
final T
<T extends View> findViewById(int id)
final T
<T extends View> findViewWithTag(Object tag)
boolean

This method is deprecated.

void
forceHasOverlappingRendering(boolean hasOverlappingRendering)
void
void
generateDisplayHash(
    String hashAlgorithm,
    Rect bounds,
    Executor executor,
    DisplayHashResultCallback callback
)
static int
View.AccessibilityDelegate
int
AccessibilityNodeProvider
CharSequence
int
int
String
String
float
Animation
Matrix
IBinder
int[]
Map<IntegerInteger>
String[]
final AutofillId
int
AutofillValue
Drawable
BlendMode
ColorStateList
PorterDuff.Mode
int
final int
float
int
float
Rect
boolean
final boolean
final ContentCaptureSession
CharSequence
final Context
ContextMenu.ContextMenuInfo
final boolean
static int
getDefaultSize(int size, int measureSpec)
Display
final int[]
Bitmap

This method is deprecated.

int

This method is deprecated.

int

This method is deprecated.

void
long
float
int
boolean
boolean
int
ArrayList<View>
getFocusables(int direction)
void
Drawable
int
BlendMode
ColorStateList
PorterDuff.Mode
boolean
getGlobalVisibleRect(Rect r, Point globalOffset)
Handler
float
float
float
float
Runnable
final boolean
final int
void
getHitRect(Rect outRect)
int
int
Drawable
Drawable
int
int
int
int
boolean
KeyEvent.DispatcherState
int
int
int
ViewGroup.LayoutParams
final int
float
int
final boolean
void
getLocationInSurface(int[] location)
void
getLocationInWindow(int[] outLocation)
void
getLocationOnScreen(int[] outLocation)
Matrix
final int
final int
final int
final int
final int
int
int
int
int
int
int
int
int
View.OnFocusChangeListener
int
ViewOutlineProvider
int
int
ViewOverlay
int
int
int
int
int
int
final ViewParent
ViewParent
float
float
PointerIcon
final List<Rect>
String[]
Resources
final boolean
final int
float
int
AttachedSurfaceControl
View
WindowInsets
float
float
float
float
float
int
int
int
int
int
int
final int
final int
int
int
final CharSequence
StateListAnimator
int
int
List<Rect>
int

This method is deprecated.

Object
int
int
CharSequence
final int
float
int
TouchDelegate
ArrayList<View>
float
String
float
float
float
long
int
int
Drawable
Drawable
int
ViewTranslationResponse
ViewTreeObserver
int
final int
int
WindowId
WindowInsetsController
int

This method is deprecated.

IBinder
int
void
float
float
float
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
static View
inflate(Context context, int resource, ViewGroup root)
void

This method is deprecated.

void
void
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean

This method is deprecated.

boolean
boolean
final boolean
final boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
final boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
View
keyboardNavigationClusterSearch(View currentCluster, int direction)
final void
measure(int widthMeasureSpec, int heightMeasureSpec)
static int[]
mergeDrawableStates(int[] baseState, int[] additionalState)
void
offsetLeftAndRight(int offset)
void
offsetTopAndBottom(int offset)
void
void
WindowInsets
void
boolean
boolean
void
void
InputConnection
void
onCreateViewTranslationRequest(
    int[] supportedFormats,
    Consumer<ViewTranslationRequest> requestsCollector
)
void
onCreateVirtualViewTranslationRequests(
    long[] virtualIds,
    int[] supportedFormats,
    Consumer<ViewTranslationRequest> requestsCollector
)
void
onDisplayHint(int hint)
boolean
void
onDraw(Canvas canvas)
void
final void
boolean
void
void
void
onFocusChanged(
    boolean gainFocus,
    int direction,
    Rect previouslyFocusedRect
)
boolean
void
onHoverChanged(boolean hovered)
boolean
void
void
boolean
onKeyDown(int keyCode, KeyEvent event)
boolean
onKeyLongPress(int keyCode, KeyEvent event)
boolean
onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
boolean
onKeyPreIme(int keyCode, KeyEvent event)
boolean
onKeyShortcut(int keyCode, KeyEvent event)
boolean
onKeyUp(int keyCode, KeyEvent event)
void
onOverScrolled(
    int scrollX,
    int scrollY,
    boolean clampedX,
    boolean clampedY
)
void
onPointerCaptureChange(boolean hasCapture)
void
void
onProvideAutofillStructure(ViewStructure structure, int flags)
void
void
void
void
ContentInfo
void
void
onRtlPropertiesChanged(int layoutDirection)
Parcelable
void
onScreenStateChanged(int screenState)
void
onScrollCaptureSearch(
    Rect localVisibleRect,
    Point windowOffset,
    Consumer<ScrollCaptureTarget> targets
)
void
onScrollChanged(int l, int t, int oldl, int oldt)
boolean
onSetAlpha(int alpha)
void
onSizeChanged(int w, int h, int oldw, int oldh)
void
boolean
void
void
void
onVisibilityAggregated(boolean isVisible)
void
onVisibilityChanged(View changedView, int visibility)
void
onWindowFocusChanged(boolean hasWindowFocus)
void

This method is deprecated.

void
onWindowVisibilityChanged(int visibility)
boolean
overScrollBy(
    int deltaX,
    int deltaY,
    int scrollX,
    int scrollY,
    int scrollRangeX,
    int scrollRangeY,
    int maxOverScrollX,
    int maxOverScrollY,
    boolean isTouchEvent
)
boolean
performAccessibilityAction(int action, Bundle arguments)
boolean
performContextClick(float x, float y)
boolean
performHapticFeedback(int feedbackConstant)
boolean
ContentInfo
void
playSoundEffect(int soundConstant)
boolean
post(Runnable action)
boolean
postDelayed(Runnable action, long delayMillis)
void
void
postInvalidateDelayed(long delayMilliseconds)
void
void
void
postOnAnimationDelayed(Runnable action, long delayMillis)
void
void
boolean
void
void
void
void
void

This method is deprecated.

final boolean
void
void
boolean
final void
final T
<T extends View> requireViewById(int id)
void
static int
resolveSize(int size, int measureSpec)
static int
resolveSizeAndState(int size, int measureSpec, int childMeasuredState)
void
final void
saveAttributeDataForStyleable(
    Context context,
    int[] styleable,
    AttributeSet attrs,
    TypedArray t,
    int defStyleAttr,
    int defStyleRes
)
void
void
scheduleDrawable(Drawable who, Runnable what, long when)
void
scrollBy(int x, int y)
void
scrollTo(int x, int y)
void
sendAccessibilityEvent(int eventType)
void
void
setAccessibilityDataSensitive(int accessibilityDataSensitive)
void
void
setAccessibilityHeading(boolean isHeading)
void
void
setAccessibilityPaneTitle(CharSequence accessibilityPaneTitle)
void
void
void
setActivated(boolean activated)
void
setAllowClickWhenDisabled(boolean clickableWhenDisabled)
void
void
void
setAlpha(float alpha)
void
void
void
setAutoHandwritingEnabled(boolean enabled)
void
setAutofillHints(String[] autofillHints)
void
void
setBackground(Drawable background)
void
setBackgroundColor(int color)
void

This method is deprecated.

void
void
void
void
final void
setBottom(int bottom)
void
setCameraDistance(float distance)
void
setClickable(boolean clickable)
void
setClipBounds(Rect clipBounds)
void
setClipToOutline(boolean clipToOutline)
void
void
setContentDescription(CharSequence contentDescription)
void
setContextClickable(boolean contextClickable)
void
setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled)
void

This method is deprecated.

void
setDrawingCacheEnabled(boolean enabled)

This method is deprecated.

void

This method is deprecated.

void
void
setElevation(float elevation)
void
setEnabled(boolean enabled)
void
setFadingEdgeLength(int length)
void
void
setFitsSystemWindows(boolean fitSystemWindows)
void
setFocusable(boolean focusable)
void
setFocusableInTouchMode(boolean focusableInTouchMode)
void
setFocusedByDefault(boolean isFocusedByDefault)
void
setForceDarkAllowed(boolean allow)
void
setForeground(Drawable foreground)
void
void
void
void
setHandwritingBoundsOffsets(
    float offsetLeft,
    float offsetTop,
    float offsetRight,
    float offsetBottom
)
void
void
setHapticFeedbackEnabled(boolean hapticFeedbackEnabled)
void
setHasTransientState(boolean hasTransientState)
void
setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled)
void
setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled)
void
void
void
setHovered(boolean hovered)
void
setId(int id)
void
void
void
void
setIsCredential(boolean isCredential)
void
setIsHandwritingDelegate(boolean isHandwritingDelegate)
void
setKeepScreenOn(boolean keepScreenOn)
void
setKeyboardNavigationCluster(boolean isCluster)
void
setLabelFor(int id)
void
void
setLayerType(int layerType, Paint paint)
void
setLayoutDirection(int layoutDirection)
void
final void
setLeft(int left)
final void
setLeftTopRightBottom(int left, int top, int right, int bottom)
void
setLongClickable(boolean longClickable)
final void
setMeasuredDimension(int measuredWidth, int measuredHeight)
void
setMinimumHeight(int minHeight)
void
setMinimumWidth(int minWidth)
void
setNestedScrollingEnabled(boolean enabled)
void
setNextClusterForwardId(int nextClusterForwardId)
void
setNextFocusDownId(int nextFocusDownId)
void
setNextFocusForwardId(int nextFocusForwardId)
void
setNextFocusLeftId(int nextFocusLeftId)
void
setNextFocusRightId(int nextFocusRightId)
void
setNextFocusUpId(int nextFocusUpId)
void
void
void
void
void
void
void
void
void
void
void
void
setOnReceiveContentListener(
    String[] mimeTypes,
    OnReceiveContentListener listener
)
void
void

This method is deprecated.

void
void
void
void
void
setOverScrollMode(int overScrollMode)
void
setPadding(int left, int top, int right, int bottom)
void
setPaddingRelative(int start, int top, int end, int bottom)
void
setPivotX(float pivotX)
void
setPivotY(float pivotY)
void
final void
setPreferKeepClear(boolean preferKeepClear)
final void
void
setPressed(boolean pressed)
void
final void
setRevealOnFocusHint(boolean revealOnFocus)
final void
setRight(int right)
void
setRotation(float rotation)
void
setRotationX(float rotationX)
void
setRotationY(float rotationY)
void
setSaveEnabled(boolean enabled)
void
setSaveFromParentEnabled(boolean enabled)
void
setScaleX(float scaleX)
void
setScaleY(float scaleY)
void
setScreenReaderFocusable(boolean screenReaderFocusable)
void
setScrollBarDefaultDelayBeforeFade(
    int scrollBarDefaultDelayBeforeFade
)
void
setScrollBarFadeDuration(int scrollBarFadeDuration)
void
setScrollBarSize(int scrollBarSize)
void
setScrollBarStyle(int style)
final void
void
void
setScrollContainer(boolean isScrollContainer)
void
setScrollIndicators(int indicators)
void
setScrollX(int value)
void
setScrollY(int value)
void
setScrollbarFadingEnabled(boolean fadeScrollbars)
void
setSelected(boolean selected)
void
setSoundEffectsEnabled(boolean soundEffectsEnabled)
void
void
void
void
setSystemUiVisibility(int visibility)

This method is deprecated.

void
void
setTextAlignment(int textAlignment)
void
setTextDirection(int textDirection)
void
final void
setTop(int top)
void
void
setTransitionAlpha(float alpha)
final void
setTransitionName(String transitionName)
void
setTransitionVisibility(int visibility)
void
setTranslationX(float translationX)
void
setTranslationY(float translationY)
void
setTranslationZ(float translationZ)
void
setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled)
void
setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled)
void
void
void
void
void
setVisibility(int visibility)
void
setWillNotCacheDrawing(boolean willNotCacheDrawing)

This method is deprecated.

void
setWillNotDraw(boolean willNotDraw)
void
setX(float x)
void
setY(float y)
void
setZ(float z)
boolean
ActionMode
void
final boolean
startDrag(
    ClipData data,
    View.DragShadowBuilder shadowBuilder,
    Object myLocalState,
    int flags
)

This method is deprecated.

final boolean
startDragAndDrop(
    ClipData data,
    View.DragShadowBuilder shadowBuilder,
    Object myLocalState,
    int flags
)
boolean
void
String
void
void
void
final void
boolean
boolean

This method is deprecated.

boolean
From android.view.ViewGroup
void
void
addExtraDataToAccessibilityNodeInfo(
    AccessibilityNodeInfo info,
    String extraDataKey,
    Bundle arguments
)
void
addFocusables(ArrayList<View> views, int direction, int focusableMode)
void
boolean
void
void
addView(View child)
boolean
addViewInLayout(View child, int index, ViewGroup.LayoutParams params)
void
attachLayoutAnimationParameters(
    View child,
    ViewGroup.LayoutParams params,
    int index,
    int count
)
void
attachViewToParent(View child, int index, ViewGroup.LayoutParams params)
void
boolean
void
void
childHasTransientStateChanged(
    View child,
    boolean childHasTransientState
)
void
void
void
void
void
debug(int depth)
void
void
void
detachViewsFromParent(int start, int count)
WindowInsets
boolean
void
void
dispatchCreateViewTranslationRequest(
    Map<AutofillId, long[]> viewIds,
    int[] supportedFormats,
    TranslationCapability capability,
    List<ViewTranslationRequest> requests
)
void
boolean
void
void
dispatchDrawableHotspotChanged(float x, float y)
void
void
boolean
boolean
boolean
boolean
boolean
boolean
void
dispatchPointerCaptureChanged(boolean hasCapture)
void
void
void
void
void
dispatchScrollCaptureSearch(
    Rect localVisibleRect,
    Point windowOffset,
    Consumer<ScrollCaptureTarget> targets
)
void
dispatchSetActivated(boolean activated)
void
dispatchSetPressed(boolean pressed)
void
dispatchSetSelected(boolean selected)
void
void

This method is deprecated.

void
boolean
boolean
boolean
dispatchUnhandledMove(View focused, int direction)
void
dispatchVisibilityChanged(View changedView, int visibility)
void
dispatchWindowFocusChanged(boolean hasFocus)
void
void
WindowInsets
WindowInsetsAnimation.Bounds
void

This method is deprecated.

void
boolean
drawChild(Canvas canvas, View child, long drawingTime)
void
void
View
OnBackInvokedDispatcher
void
findViewsWithText(
    ArrayList<View> outViews,
    CharSequence text,
    int flags
)
View
focusSearch(View focused, int direction)
void
boolean
View
getChildAt(int index)
int
int
getChildDrawingOrder(int childCount, int drawingPosition)
static int
getChildMeasureSpec(int spec, int padding, int childDimension)
boolean
boolean
getChildVisibleRect(View child, Rect r, Point offset)
boolean
boolean
int
View
LayoutAnimationController
Animation.AnimationListener
int
LayoutTransition
int
ViewGroupOverlay
int

This method is deprecated.

boolean
boolean
boolean
int
final void
invalidateChild(View child, Rect dirty)

This method is deprecated.

ViewParent
invalidateChildInParent(int[] location, Rect dirty)

This method is deprecated.

boolean

This method is deprecated.

boolean

This method is deprecated.

boolean
boolean

This method is deprecated.

boolean
boolean
boolean
void
final void
layout(int l, int t, int r, int b)
void
measureChild(
    View child,
    int parentWidthMeasureSpec,
    int parentHeightMeasureSpec
)
void
measureChildWithMargins(
    View child,
    int parentWidthMeasureSpec,
    int widthUsed,
    int parentHeightMeasureSpec,
    int heightUsed
)
void
measureChildren(int widthMeasureSpec, int heightMeasureSpec)
void
notifySubtreeAccessibilityStateChanged(
    View child,
    View source,
    int changeType
)
final void
final void
int[]
onCreateDrawableState(int extraSpace)
void
boolean
boolean
boolean
onNestedFling(
    View target,
    float velocityX,
    float velocityY,
    boolean consumed
)
boolean
onNestedPreFling(View target, float velocityX, float velocityY)
boolean
onNestedPrePerformAccessibilityAction(
    View target,
    int action,
    Bundle args
)
void
onNestedPreScroll(View target, int dx, int dy, int[] consumed)
void
onNestedScroll(
    View target,
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed
)
void
onNestedScrollAccepted(View child, View target, int axes)
boolean
onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)
boolean
PointerIcon
onResolvePointerIcon(MotionEvent event, int pointerIndex)
boolean
onStartNestedScroll(View child, View target, int nestedScrollAxes)
void
void
void
void
void
void
void
removeDetachedView(View child, boolean animate)
void
void
removeViewAt(int index)
void
void
removeViews(int start, int count)
void
removeViewsInLayout(int start, int count)
void
requestChildFocus(View child, View focused)
boolean
requestChildRectangleOnScreen(
    View child,
    Rect rectangle,
    boolean immediate
)
void
requestDisallowInterceptTouchEvent(boolean disallowIntercept)
boolean
requestFocus(int direction, Rect previouslyFocusedRect)
boolean
void
boolean
void
void
setAddStatesFromChildren(boolean addsStates)
void

This method is deprecated.

void
setAnimationCacheEnabled(boolean enabled)

This method is deprecated.

void

This method is deprecated.

void
void

This method is deprecated.

void
setClipChildren(boolean clipChildren)
void
setClipToPadding(boolean clipToPadding)
void
setDescendantFocusability(int focusability)
void
void
void
setLayoutMode(int layoutMode)
void
void
void
void
setPersistentDrawingCache(int drawingCacheToKeep)

This method is deprecated.

void
void
setTouchscreenBlocksFocus(boolean touchscreenBlocksFocus)
void
setTransitionGroup(boolean isTransitionGroup)
void
boolean
ActionMode
startActionModeForChild(
    View originalView,
    ActionMode.Callback callback
)
void
void
void
suppressLayout(boolean suppress)
void

Public constructors

PreviewView

Added in 1.1.0
@UiThread
public PreviewView(@NonNull Context context)

PreviewView

Added in 1.1.0
@UiThread
public PreviewView(@NonNull Context context, @Nullable AttributeSet attrs)

PreviewView

Added in 1.1.0
@UiThread
public PreviewView(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)

PreviewView

Added in 1.1.0
@UiThread
public PreviewView(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr,
    int defStyleRes
)

Public methods

getBitmap

Added in 1.1.0
@UiThread
public @Nullable Bitmap getBitmap()

Returns a Bitmap representation of the content displayed on the PreviewView, or null if the camera preview hasn't started yet.

The returned Bitmap uses the ARGB_8888 pixel format and its dimensions are the same as this view's.

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

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

If the preview hasn't started yet, the method may return null or an empty Bitmap. Use getPreviewStreamState to get the StreamState and wait for STREAMING to make sure the preview is started.

Returns
@Nullable Bitmap

A ARGB_8888Bitmap representing the content displayed on the PreviewView, or null if the camera preview hasn't started yet.

getController

Added in 1.1.0
@UiThread
public @Nullable CameraController getController()

Get the CameraController.

getImplementationMode

Added in 1.1.0
@UiThread
public @NonNull PreviewView.ImplementationMode getImplementationMode()

Returns the ImplementationMode.

If nothing is set via setImplementationMode, the default value is PERFORMANCE.

getMeteringPointFactory

Added in 1.1.0
@UiThread
public @NonNull MeteringPointFactory getMeteringPointFactory()

Gets the MeteringPointFactory for the camera currently connected to the PreviewView, if any.

The returned MeteringPointFactory is capable of creating MeteringPoints from (x, y) coordinates in the PreviewView. This conversion takes into account its ScaleType. The MeteringPointFactory is automatically adjusted if the PreviewView layout or the ScaleType changes.

The MeteringPointFactory returns invalid MeteringPoint if the preview is not ready, or the PreviewView dimension is zero. The invalid MeteringPoint will cause startFocusAndMetering to fail but it won't crash the application. Wait for the STREAMING state to make sure the preview is ready.

getOutputTransform

Added in 1.1.0
public @Nullable OutputTransform getOutputTransform()

Gets the OutputTransform associated with the PreviewView.

Returns a OutputTransform object that represents the transform being applied to the associated Preview use case. Returns null if the transform info is not ready. For example, when the associated Preview has not been bound or the PreviewView's layout is not ready.

PreviewView needs to be in COMPATIBLE mode for the transform to work correctly. For example, the returned OutputTransform may not respect the value of getMatrix when PERFORMANCE mode is used.

Returns
@Nullable OutputTransform

the transform applied on the preview by this PreviewView.

getPreviewStreamState

Added in 1.1.0
public @NonNull LiveData<PreviewView.StreamStategetPreviewStreamState()

Gets a LiveData for the preview StreamState.

There are two preview stream states, IDLE and STREAMING. IDLE indicates the preview is currently not visible and streaming is stopped. STREAMING means the preview is streaming or is about to start streaming. This state guarantees the preview is visible only when the ImplementationMode is COMPATIBLE. When in PERFORMANCE mode, it is possible the preview becomes visible slightly after the state changes to STREAMING.

Apps that require a precise signal for when the preview starts should set the implementation mode to COMPATIBLE.

Returns
@NonNull LiveData<PreviewView.StreamState>

A LiveData of the preview's StreamState. Apps can get the current state with getValue, or register an observer with observe .

getScaleType

Added in 1.1.0
@UiThread
public @NonNull PreviewView.ScaleType getScaleType()

Returns the ScaleType currently applied to the preview.

The default value is FILL_CENTER.

Returns
@NonNull PreviewView.ScaleType

The ScaleType currently applied to the preview.

getScreenFlash

Added in 1.4.0
@ExperimentalPreviewViewScreenFlash
@UiThread
public @Nullable ImageCapture.ScreenFlash getScreenFlash()

Returns an ImageCapture.ScreenFlash implementation based on the Window instance set via setScreenFlashWindow.

This API uses an internally managed ScreenFlashView to provide the ImageCapture.ScreenFlash implementation which can be passed to the setScreenFlash API. The following example shows the API usage.

mPreviewView.setScreenFlashWindow(activity.getWindow());
mImageCapture.setScreenFlash(mPreviewView.getScreenFlash());
mImageCapture.setFlashMode(ImageCapture.FLASH_MODE_SCREEN);
mImageCapture.takePhoto(mCameraExecutor, mOnImageSavedCallback);
Returns
@Nullable ImageCapture.ScreenFlash

An ImageCapture.ScreenFlash implementation provided by getScreenFlash which can be null if a non-null Window instance hasn't been set.

getSensorToViewTransform

Added in 1.4.0
@UiThread
public @Nullable Matrix getSensorToViewTransform()

Gets the transformation matrix from camera sensor to PreviewView.

The value is a mapping from sensor coordinates to PreviewView coordinates, which is, from the rect of SENSOR_INFO_ACTIVE_ARRAY_SIZE to the rect defined by (0, 0, PreviewView#getWidth(), PreviewView#getHeight()). The app can use the matrix to map the coordinates from one UseCase to another. For example, detecting face with ImageAnalysis, and then highlighting the face in PreviewView.

This method returns null if the transformation is not ready. It happens when PreviewView layout has not been measured, or the associated Preview use case is not yet bound to a camera. For the former case, the app can listen to the layout change via e.g. addOnLayoutChangeListener. For the latter case, the app wait until the Preview or CameraController is bound and the LifecycleOwner is in the STARTED state. The app should call this method to get the latest value before performing coordinates transformation.

The return value does not include the custom transform applied by the app via methods like setScaleX.

getSurfaceProvider

Added in 1.1.0
@UiThread
public @NonNull Preview.SurfaceProvider getSurfaceProvider()

Gets a Preview.SurfaceProvider to be used with setSurfaceProvider. This allows the camera feed to start when the Preview use case is bound to a lifecycle.

The returned Preview.SurfaceProvider will provide a preview Surface to the camera that's either managed by a TextureView or SurfaceView depending on the ImplementationMode and the device's attributes (e.g. API level, camera hardware support level).

Returns
@NonNull Preview.SurfaceProvider

A Preview.SurfaceProvider to attach to a Preview use case.

getViewPort

Added in 1.1.0
@UiThread
public @Nullable ViewPort getViewPort()

Gets a ViewPort based on the current status of PreviewView.

Returns a ViewPort instance based on the PreviewView's current width, height, layout direction, scale type and display rotation. By using the ViewPort, all the UseCases in the UseCaseGroup will have the same output image that also matches the aspect ratio of the PreviewView.

Returns
@Nullable ViewPort

null if the view is not currently attached or the view's width/height is zero.

getViewPort

Added in 1.1.0
@UiThread
public @Nullable ViewPort getViewPort(int targetRotation)

Gets a ViewPort with custom target rotation.

Returns a ViewPort instance based on the PreviewView's current width, height, layout direction, scale type and the given target rotation.

Use this method if Preview's desired rotation is not the default display rotation. For example, when remote display is in use and the desired rotation for the remote display is based on the accelerometer reading. In that case, use android.view.OrientationEventListener to obtain the target rotation and create ViewPort as following:

ORIENTATION_UNKNOWN: orientation == -1

ROTATION_0: orientation >= 315 || orientation <45

ROTATION_90: orientation >= 225 &&orientation <315

ROTATION_180: orientation >= 135 &&orientation <225

ROTATION_270: orientation >= 45 &&orientation <135

Once the target rotation is obtained, use it with setTargetRotation to update the rotation. Example:

Preview preview = new Preview.Builder().setTargetRotation(targetRotation).build();
ViewPort viewPort = previewView.getViewPort(targetRotation);
UseCaseGroup useCaseGroup =
    new UseCaseGroup.Builder().setViewPort(viewPort).addUseCase(preview).build();
cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, useCaseGroup);

Note that for non-display rotation to work, the mode must be set to COMPATIBLE.

Parameters
int targetRotation

A rotation value, expressed as one of ROTATION_0, ROTATION_90, ROTATION_180, or ROTATION_270.

Returns
@Nullable ViewPort

null if the view's width/height is zero.

onTouchEvent

public boolean onTouchEvent(@NonNull MotionEvent event)

performClick

public boolean performClick()

setController

Added in 1.1.0
@UiThread
public void setController(@Nullable CameraController cameraController)

Sets the CameraController.

Once set, the controller will use PreviewView to display camera preview feed. It also uses the PreviewView's layout dimension to set the crop rect for all the use cases so that the output from other use cases match what the end user sees in PreviewView. It also enables features like tap-to-focus and pinch-to-zoom.

Setting it to null or to a different CameraController stops the previous CameraController from working. The previous CameraController will remain detached until it's set on the PreviewView again.

Throws
java.lang.IllegalArgumentException

If the CameraController's camera selector is unable to resolve a camera to be used for the enabled use cases.

See also
CameraController

setImplementationMode

Added in 1.1.0
@UiThread
public void setImplementationMode(
    @NonNull PreviewView.ImplementationMode implementationMode
)

Sets the ImplementationMode for the PreviewView.

PreviewView displays the preview with a TextureView when the mode is COMPATIBLE, and tries to use a SurfaceView if it is PERFORMANCE when possible, which depends on the device's attributes (e.g. API level, camera hardware support level). If not set, the default mode is PERFORMANCE.

This method needs to be called before the Preview.SurfaceProvider is set on Preview. Once changed, Preview.SurfaceProvider needs to be set again. e.g. preview.setSurfaceProvider(previewView.getSurfaceProvider()).

setScaleType

Added in 1.1.0
@UiThread
public void setScaleType(@NonNull PreviewView.ScaleType scaleType)

Applies a ScaleType to the preview.

If a CameraController is attached to PreviewView, the change will take immediate effect. It also takes immediate effect if getViewPort is not set in the bound UseCaseGroup. Otherwise, the UseCases need to be bound again with the latest value of getViewPort.

This value can also be set in the layout XML file via the app:scaleType attribute.

The default value is FILL_CENTER.

name app:scaleType

Parameters
@NonNull PreviewView.ScaleType scaleType

A ScaleType to apply to the preview.

setScreenFlashOverlayColor

Added in 1.4.0
@ExperimentalPreviewViewScreenFlash
public void setScreenFlashOverlayColor(@ColorInt int color)

Sets the color of the top overlay view during screen flash.

Parameters
@ColorInt int color

The color value of the top overlay.

setScreenFlashWindow

Added in 1.4.0
@UiThread
public void setScreenFlashWindow(@Nullable Window screenFlashWindow)

Sets a Window instance for subsequent photo capture requests with FLASH_MODE_SCREEN set.

The calling of this API will take effect for FLASH_MODE_SCREEN only and the Window will be ignored for other flash modes. During screen flash photo capture, the window is used for the purpose of changing brightness.

If the implementation provided by the user is no longer valid (e.g. due to any android.app.Activity or android.view.View reference used in the implementation becoming invalid), user needs to re-set a new valid window or clear the previous one with setScreenFlashWindow(null), whichever appropriate.

For most app scenarios, a Window instance can be obtained from getWindow. In case of a fragment, getActivity can first be used to get the activity instance.

Parameters
@Nullable Window screenFlashWindow

A Window instance that is used to change the brightness during screen flash photo capture.

Protected methods

onAttachedToWindow

protected void onAttachedToWindow()

onDetachedFromWindow

protected void onDetachedFromWindow()