English | Site Directory

Android - An Open Handset Alliance Project

android.view
public class

android.view.View

java.lang.Object
android.view.View Drawable.Callback KeyEvent.Callback

The View class represents the basic UI building block. A view occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, used to create interactive graphical user interfaces.

Using Views

All of the views in a window are arranged in a single tree. You can add views either from code or by specifying a tree of views in one or more XML layout files. There are many specialized subclasses of views that act as controls or are capable of displaying text, images, or other content.

Once you have created a tree of views, there are typically a few types of common operations you may wish to perform:

  • Set properties: for example setting the text of a TextView. The available properties and the methods that set them will vary among the different subclasses of views. Note that properties that are known at build time can be set in the XML layout files.
  • Set focus: The framework will handled moving focus in response to user input. To force focus to a specific view, call requestFocus().
  • Set up listeners: Views allow clients to set listeners that will be notified when something interesting happens to the view. For example, all views will let you set a listener to be notified when the view gains or loses focus. You can register such a listener using setOnFocusChangeListener(View.OnFocusChangeListener). Other view subclasses offer more specialized listeners. For example, a Button exposes a listener to notify clients when the button is clicked.
  • Set visibility: You can hide or show views using setVisibility(int).

Note: The Android framework is responsible for measuring, laying out and drawing views. You should not call methods that perform these actions on views yourself unless you are actually implementing a ViewGroup.

Implementing a Custom View

To implement a custom view, you will usually begin by providing overrides for some of the standard methods that the framework calls on all views. You do not need to override all of these methods. In fact, you can start by just overriding onDraw(android.graphics.Canvas).
Category Methods Description
Creation Constructors There is a form of the constructor that are called when the view is created from code and a form that is called when the view is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file.
onFinishInflate() Called after a view and all of its children has been inflated from XML.
Layout onMeasure(int, int) Called to determine the size requirements for this view and all of its children.
onLayout(boolean, int, int, int, int) Called when this view should assign a size and position to all of its children.
onSizeChanged(int, int, int, int) Called when the size of this view has changed.
Drawing onDraw(Canvas) Called when the view should render its content.
Event processing onKeyDown(int, KeyEvent) Called when a new key event occurs.
onKeyUp(int, KeyEvent) Called when a key up event occurs.
onTrackballEvent(MotionEvent) Called when a trackball motion event occurs.
onTouchEvent(MotionEvent) Called when a touch screen motion event occurs.
Focus onFocusChanged(boolean, int, Rect) Called when the view gains or loses focus.
onWindowFocusChanged(boolean) Called when the window containing the view gains or loses focus.
Attaching onAttachedToWindow() Called when the view is attached to a window.
onDetachedFromWindow() Called when the view is detached from its window.
onWindowVisibilityChanged(int) Called when the visibility of the window containing the view has changed.

IDs

Views may have an integer id associated with them. These ids are typically assigned in the layout XML files, and are used to find specific views within the view tree. A common pattern is to:
  • Define a Button in the layout file and assign it a unique ID.
     <Button id="@+id/my_button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="@string/my_button_text"/>
     
  • From the onCreate method of an Activity, find the Button
          Button myButton = (Button) findViewById(R.id.my_button);
     

View IDs need not be unique throughout the tree, but it is good practice to ensure that they are at least unique within the part of the tree you are searching.

Position

The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth() (see Size for more information about the width.)

Size, padding and margins

The size of a view is expressed with a width and a height. A view actually possess two pairs of width and height values.

The first pair is known as measured width and measured height. These dimensions define how big a view wants to be within its parent (see Layout for more details.) The measured dimensions can be obtained by calling getMeasuredWidth() and getMeasuredHeight().

The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, be different from the measured width and height. The width and height can be obtained by calling getWidth() and getHeight().

To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom().

Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.

Layout

Layout is a two pass process: a measure pass and a layout pass. The measuring pass is implemented in measure(int, int) and is a top-down traversal of the view tree. Each view pushes dimension specifications down the tree during the recursion. At the end of the measure pass, every view has stored its measurements. The second pass happens in layout(int, int, int, int) and is also top-down. During this pass each parent is responsible for positioning all of its children using the sizes computed in the measure pass.

When a view's measure() method returns, its getMeasuredWidth() and getMeasuredHeight() values must be set, along with those for all of that view's descendants. A view's measured width and measured height values must respect the constraints imposed by the view's parents. This guarantees that at the end of the measure pass, all parents accept all of their children's measurements. A parent view may call measure() more than once on its children. For example, the parent may measure each child once with unspecified dimensions to find out how big they want to be, then call measure() on them again with actual numbers if the sum of all the children's unconstrained sizes is too big or too small.

The measure pass uses two classes to communicate dimensions. The View.MeasureSpec class is used by views to tell their parents how they want to be measured and positioned. The base LayoutParams class just describes how big the view wants to be for both width and height. For each dimension, it can specify one of:

  • an exact number
  • FILL_PARENT, which means the view wants to be as big as its parent (minus padding)
  • WRAP_CONTENT, which means that the view wants to be just big enough to enclose its content (plus padding).
There are subclasses of LayoutParams for different subclasses of ViewGroup. For example, AbsoluteLayout has its own subclass of LayoutParams which adds an X and Y value.

MeasureSpecs are used to push requirements down the tree from parent to child. A MeasureSpec can be in one of three modes:

  • UNSPECIFIED: This is used by a parent to determine the desired dimension of a child view. For example, a LinearLayout may call measure() on its child with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how tall the child view wants to be given a width of 240 pixels.
  • EXACTLY: This is used by the parent to impose an exact size on the child. The child must use this size, and guarantee that all of its descendants will fit within this size.
  • AT_MOST: This is used by the parent to impose a maximum size on the child. The child must gurantee that it and all of its descendants will fit within this size.

To intiate a layout, call requestLayout(). This method is typically called by a view on itself when it believes that is can no longer fit within its current bounds.

Drawing

Drawing is handled by walking the tree and rendering each view that intersects the the invalid region. Because the tree is traversed in-order, this means that parents will draw before (i.e., behind) their children, with siblings drawn in the order they appear in the tree.

The framework will not draw views that are not in the invalid region, and also will take care of drawing the views background for you.

To force a view to draw, call invalidate().

Event Handling and Threading

The basic cycle of a view is as follows:

  1. An event comes in and is dispatched to the appropriate view. The view handles the event and notifies any listeners.
  2. If in the course of processing the event, the view's bounds may need to be changed, the view will call requestLayout().
  3. Similarly, if in the course of processing the event the view's appearance may need to be changed, the view will call invalidate().
  4. If either requestLayout() or invalidate() were called, the framework will take care of measuring, laying out, and drawing the tree as appropriate.

Note: The entire view tree is single threaded. You must always be on the UI thread when calling any method on any view. If you are doing work on other threads and want to update the state of a view from that thread, you should use a Handler.

Focus Handling

The framework will handle routine focus movement in response to user input. This includes changing the focus as views are removed or hidden, or as new views become available. Views indicate their willingness to take focus through the isFocusable() method. To change whether a view can take focus, call setFocusable(boolean). When in touch mode (see notes below) views indicate whether they still would like focus via isFocusableInTouchMode() and can change this via setFocusableInTouchMode(boolean).

Focus movement is based on an algorithm which finds the nearest neighbor in a given direction. In rare cases, the default algorithm may not match the intended behavior of the developer. In these situations, you can provide explicit overrides by using these XML attributes in the layout file:

 nextFocusDown
 nextFocusLeft
 nextFocusRight
 nextFocusUp
 

Views indicate their preference for receiving focus over their descendants via the getFocusType() method. NORMAL_FOCUS (the default), indicates it will give itself focus before looking in descendants. WEAK_FOCUS indicates that it will try to give focus to its descendants before trying itself. This focus dispatch logic is implemented for you in requestFocus(int, android.graphics.Rect)

To get a particular view to take focus, call requestFocus().

Touch Mode

When a user is navigating a user interface via directional keys such as a D-pad, it is necessary to give focus to actionable items such as buttons so the user can see what will take input. If the device has touch capabilities, however, and the user begins interacting with the interface by touching it, it is no longer necessary to always highlight, or give focus to, a particular view. This motivates a mode for interaction named 'touch mode'.

For a touch capable device, once the user touches the screen, the device will enter touch mode. From this point onward, only views for which isFocusableInTouchMode() is true will be focusable, such as text editing widgets. Other views that are touchable, like buttons, will not take focus when touched; they will only fire the on click listeners.

Any time a user hits a directional key, such as a D-pad direction, the view device will exit touch mode, and find a view to take focus, so that the user may resume interacting with the user interface without touching the screen again.

The touch mode state is maintained across Activitys. Call inTouchMode() to see whether the device is currently in touch mode.

Scrolling

The framework provides basic support for views that wish to internally scroll their content. This includes keeping track of the X and Y scroll offset as well as mechanisms for drawing scrollbars. See scrollBy(int, int), scrollTo(int, int), and awakenScrollBars() for more details.

Tags

Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.

Animation

You can attach an Animation object to a view using setAnimation(Animation) or startAnimation(Animation). The animation can alter the scale, rotation, translation and alpha of a view over time. If the animation is attached to a view that has children, the animation will affect the entire subtree rooted by that node. When an animation is started, the framework will take care of redrawing the appropriate views until the animation completes.

Nested Classes
View.CheckForKeyLongPress  
View.MeasureSpec A MeasureSpec encapsulates the layout requirements passed from parent to child. 
View.OnClickListener Interface definition for a callback to be invoked when a view is clicked. 
View.OnFocusChangeListener Interface definition for a callback to be invoked when the focus state of a view changed. 
View.OnKeyListener Interface definition for a callback to be invoked when a key event is dispatched to this view. 
View.OnLongClickListener Interface definition for a callback to be invoked when a view has been clicked and held. 
View.OnPopulateContextMenuListener Interface definition for a callback to be invoked when the context menu for this view is being built. 
Known Direct Subclasses
Known Indirect Subclasses

See Also

Summary

XML Attributes

Attribute name Related methods  
android:background setBackground(int)
 
A drawable to use as the background. 
android:clickable setClickable(boolean)
 
Defines whether this view reacts to click events. 
android:drawingCacheQuality setDrawingCacheQuality(int)
 
Defines the quality of translucent drawing caches. 
android:fadingEdge setVerticalFadingEdgeEnabled(boolean)
 
Defines which edges should be fadeded on scrolling. 
android:fadingEdgeLength getVerticalFadingEdgeLength()
 
Defines the length of the fading edges. 
android:fitStatusBar   Boolean internal attribute to adjust view layout based on the status bar location. 
android:focusType setFocusType(int)
 
Sets the circumstances under which this view will take focus. 
android:focusable setFocusable(boolean)
 
Boolean that controls whether a view can take focus. 
android:focusableInTouchMode setFocusableInTouchMode(boolean)
 
Boolean that controls whether a view can take focus while in touch mode. 
android:freezeDisabled setFreezeDisabled(boolean)
 
If set, no icicle will be saved for this view when it is being frozen. 
android:id setId(int)
 
Supply an identifier name for this view, to later retrieve it with View.findViewById() or Activity.findViewById()
android:nextFocusDown   Defines the next view to give focus to when the next focus is FOCUS_DOWN If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed. 
android:nextFocusLeft   Defines the next view to give focus to when the next focus is FOCUS_LEFT
android:nextFocusRight   Defines the next view to give focus to when the next focus is FOCUS_RIGHT If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed. 
android:nextFocusUp   Defines the next view to give focus to when the next focus is FOCUS_UP If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed. 
android:padding setPadding(int,int,int,int)
 
Sets the padding, in pixels, of all four edges. 
android:paddingBottom setPadding(int,int,int,int)
 
Sets the padding, in pixels, of the bottom edge; see padding
android:paddingLeft setPadding(int,int,int,int)
 
Sets the padding, in pixels, of the left edge; see padding
android:paddingRight setPadding(int,int,int,int)
 
Sets the padding, in pixels, of the right edge; see padding
android:paddingTop setPadding(int,int,int,int)
 
Sets the padding, in pixels, of the top edge; see padding
android:scrollX   The initial horizontal scroll offset, in pixels. 
android:scrollY   The initial vertical scroll offset, in pixels. 
android:scrollbarDefaultDelayBeforeFade   Delay in milliseconds before the scrollbars disappear. 
android:scrollbarFadeDuration   Duration in milliseconds of the fade when the scrollbars disappear. 
android:scrollbarSize   Sets the width of vertical scrollbars and height of horizontal scrollbars. 
android:scrollbarThumbHorizontal   Drawable for horizontal scrollbars' thumb. 
android:scrollbarThumbVertical   Drawable for vertical scrollbars' thumb. 
android:scrollbarTrackHorizontal   Drawable for horizontal scrollbars' track. 
android:scrollbarTrackVertical   Drawable for vertical scrollbars' track. 
android:scrollbars   Defines which scrollbars should be displayed on scrolling or not. 
android:visibility setVisibility(int)
 
Controls the initial visibility of the view. 

Constants

      Value  
int  DRAWING_CACHE_QUALITY_AUTO 

Enables automatic quality mode for the drawing cache. 

0x00000000 
int  DRAWING_CACHE_QUALITY_HIGH 

Enables high quality mode for the drawing cache. 

1048576  0x00100000 
int  DRAWING_CACHE_QUALITY_LOW 

Enables low quality mode for the drawing cache. 

524288  0x00080000 
int  FOCUS_BACKWARD  Use with focusSearch(int) 0x00000001 
int  FOCUS_DOWN  Use with focusSearch(int) 130  0x00000082 
int  FOCUS_FORWARD  Use with focusSearch(int) 0x00000002 
int  FOCUS_LEFT  Use with focusSearch(int) 17  0x00000011 
int  FOCUS_RIGHT  Use with focusSearch(int) 66  0x00000042 
int  FOCUS_UP  Use with focusSearch(int) 33  0x00000021 
int  GONE  This view is invisible, and it doesn't take any space for layout purposes.  0x00000008 
int  INVISIBLE  This view is invisible, but it still takes up space for layout purposes.  0x00000004 
int  NORMAL_FOCUS  This view wants keystrokes.  0x00000000 
int  NO_ID  Used to mark a View that has no ID.  -1  0xffffffff 
String  VIEW_LOG_TAG  The logging tag used by this class with android.util.Log.  "View" 
int  VISIBLE  This view is visible.  0x00000000 
int  WEAK_FOCUS  This view wants keystrokes, but only if none of its children has focus.  0x00000002 

Fields

protected      int  mBottom  The distance in pixels from the top edge of this view's parent to the bottom edge of this view. 
protected      Context  mContext  The application environment this view lives in. 
protected      LayoutParams  mLayoutParams  The layout parameters associated with this view and used by the parent ViewGroup to determine how this view should be laid out. 
protected      int  mLeft  The distance in pixels from the left edge of this view's parent to the left edge of this view. 
protected    final  int[]  mLocation  Used to store a pair of coordinates, for instance returned values returned by getLocationInWindow(int[])
protected      OnClickListener  mOnClickListener  Listener used to dispatch click events. 
protected      OnFocusChangeListener  mOnFocusChangeListener  Listener used to dispatch focus change events. 
protected      OnLongClickListener  mOnLongClickListener  Listener used to dispatch long click events. 
protected      OnPopulateContextMenuListener  mOnPopulateContextMenuListener  Listener used to build the context menu. 
protected      int  mPaddingBottom  The bottom padding in pixels, that is the distance in pixels between the bottom edge of this view and the bottom edge of its content. 
protected      int  mPaddingLeft  The left padding in pixels, that is the distance in pixels between the left edge of this view and the left edge of its content. 
protected      int  mPaddingRight  The right padding in pixels, that is the distance in pixels between the right edge of this view and the right edge of its content. 
protected      int  mPaddingTop  The top padding in pixels, that is the distance in pixels between the top edge of this view and the top edge of its content. 
protected      ViewParent  mParent  The parent this view is attached to. 
protected      int  mRight  The distance in pixels from the left edge of this view's parent to the right edge of this view. 
protected      int  mScrollX  The offset, in pixels, by which the content of this view is scrolled horizontally. 
protected      int  mScrollY  The offset, in pixels, by which the content of this view is scrolled vertically. 
protected      Object  mTag  The view's tag. 
protected      int  mTop  The distance in pixels from the top edge of this view's parent to the top edge of this view. 

Public Constructors

          View(Context context)
Simple constructor to use when creating a view from code.
          View(Context context, AttributeSet attrs, Map inflateParams)
Constructor that is called when inflating a view from XML.
          View(Context context, AttributeSet attrs, Map inflateParams, int defStyle)
Perform inflation from XML and apply a class-specific base style.

Public Methods

        void  bringToFront()
Change the view's z order in the tree, so it's on top of other sibling views
        void  buildDrawingCache()

Forces the drawing cache to be built if the drawing cache is enabled and if it has not been built yet.

        void  clearAnimation()
Cancels any animations for this view.
        void  clearFocus()
Called when this view wants to give up focus.
        void  computeScroll()
Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.
        Bitmap  copyWindowBitmap()
Return a copy of the bitmap holding the overall contents of the window this view is attached to.
        boolean  dispatchKeyEvent(KeyEvent event)
Dispatch a key event to the next view on the focus path.
        boolean  dispatchTouchEvent(MotionEvent event)
Pass the touch screen motion event down to the target view, or this view if it is the target.
        boolean  dispatchTrackballEvent(MotionEvent event)
Pass a trackball motion event down to the focused view.
        boolean  dispatchUnhandledMove(View focused, int direction)
This method is the last chance for the focused view and its ancestors to respond to an arrow key.
        void  dispatchWindowFocusChanged(boolean hasFocus)
Called when the window containing this view gains or loses window focus.
        void  dispatchWindowVisibilityChanged(int visibility)
Dispatch a window visibility change down the view hierarchy.
        void  draw(Canvas canvas)
Manually render this view (and all of its children) to the given Canvas.
        View  findFocus()
Find the view in the hierarchy rooted at this view that currently has focus.
    final    View  findViewById(int id)
Look for a child view with the given id.
    final    View  findViewWithTag(Object tag)
Look for a child view with the given tag.
        View  focusSearch(int direction)
Find the nearest view in the specified direction that can take focus.
        void  freeze(SparseArray container)
Store this view hierarchy's frozen state into the given container.
        void  getAbsoluteLocationOnScreen(int[] location)

Computes the coordinates of this view on the screen.

        Animation  getAnimation()
Get the animation currently associated with this view.
        Drawable  getBackground()
Gets the background drawable
        int  getBaseline()

Return the offset of the widget's text baseline from the widget's top boundary.

        boolean  getBlockDescendantFocus()
Indicated if this view will block its descendants from receiving or requesting focus.
        boolean  getBlockUnmatchedKeyUps()
Indicates whether this view will receive key up events for which it did not receive the corresponding key down.
    final    int  getBottom()
Bottom position of this view relative to its parent.
    final    Context  getContext()
Returns the context the view is running in, through which it can access the current theme, resources, etc.
        int  getDefaultSize(int size, int measureSpec)
Utility to return a default size.
    final    int[]  getDrawableState()
Return an array of resource IDs of the drawable states representing the current state of the view.
        Bitmap  getDrawingCache()

Returns the bitmap in which this view drawing is cached.

        int  getDrawingCacheQuality()
Returns the quality of the drawing cache.
        void  getDrawingRect(Rect outRect)
Return the visible drawing bounds of your view.
        long  getDrawingTime()

Return the time at which the drawing of the view hierarchy started.

        int  getFocusType()
Gets the conditions under which this view will take focus.
        ArrayList  getFocusables()
Find and return all focusable views that are descendants of this view, possibly including this view if it is focusable itself.
        void  getFocusedRect(Rect r)
When a view has focus and the user navigates away from it, the next view is searched for starting from the rectangle filled in by this method.
        boolean  getGlobalVisibleRect(Rect r, Point globalOffset)
If some part of this view is not clipped by any of its parents, then return that area in r in global (root) coordinates.
    final    boolean  getGlobalVisibleRect(Rect r)
    final    int  getHeight()
Return the height of your view.
        void  getHitRect(Rect outRect)
Hit rectangle in parent's coordinates
        int  getHorizontalFadingEdgeLength()
        int  getHorizontalScrollbarHeight()
        int  getId()
Returns this view's identifier.
      static  long  getInstanceCount()
        LayoutParams  getLayoutParams()
Get the LayoutParams associated with this view.
    final    int  getLeft()
Left position of this view relative to its parent.
    final    boolean  getLocalVisibleRect(Rect r)
        void  getLocationInWindow(int[] location)

Computes the coordinates of this view in its window.

        void  getLocationOnScreen(int[] location)

Computes the coordinates of this view on the screen.

    final    int  getMeasuredHeight()
The height of this view as measured in the most recent call to measure().
    final    int  getMeasuredWidth()
The width of this view as measured in the most recent call to measure().
        OnFocusChangeListener  getOnFocusChangeListener()
Returns the focus-change callback registered for this view.
        int  getPaddingBottom()
Returns the bottom padding of this view.
        int  getPaddingLeft()
Returns the left padding of this view.
        int  getPaddingRight()
Returns the right padding of this view.
        int  getPaddingTop()
Returns the top padding of this view.
    final    ViewParent  getParent()
Gets the parent of this view.
        Resources  getResources()
Returns the resources associated with this view.
    final    int  getRight()
Right position of this view relative to its parent.
        View  getRootView()

Finds the topmost view in the current view hierarchy.

    final    int  getScrollX()
Return the scrolled left position of this view.
    final    int  getScrollY()
Return the scrolled top position of this view.
        Object  getTag()
Returns this view's tag.
    final    int  getTop()
Top position of this view relative to its parent.
        int  getVerticalFadingEdgeLength()
        int  getVerticalScrollbarWidth()
      static  long  getViewRootInstanceCount()
        int  getVisibility()
Returns the visibility status for this view.
    final    int  getWidth()
Return the width of the your view.