Android.Views.View Class

Developer Guides

For information about using this class to develop your application's user interface, read the User Interface developer guide.

See Also: View Members

Syntax

[Android.Runtime.Register("android/view/View", DoNotGenerateAcw=true)]
public class View : Java.Lang.Object, Android.Graphics.Drawables.Drawable.ICallback, Android.Views.Accessibility.IAccessibilityEventSource, KeyEvent.ICallback, IDisposable

Remarks

Developer Guides

For information about using this class to develop your application's user interface, read the User Interface developer guide.

Using Views

Implementing a Custom View

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:

Position

Size, padding and margins

Layout

Drawing

Event Handling and Threading

Focus Handling

Touch Mode

Scrolling

Tags

Properties

Animation

Security

This class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). The Android.Views.ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views (or other ViewGroups) and define their layout properties.

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:

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 Android.Views.ViewGroup.

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 View.OnDraw(Android.Graphics.Canvas).
CategoryMethodsDescription
CreationConstructorsThere 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.
View.OnFinishInflateCalled after a view and all of its children has been inflated from XML.
LayoutView.OnMeasure(int, System.Int32)Called to determine the size requirements for this view and all of its children.
View.OnLayout(bool, System.Int32, System.Int32, System.Int32, System.Int32)Called when this view should assign a size and position to all of its children.
View.OnSizeChanged(int, System.Int32, System.Int32, System.Int32)Called when the size of this view has changed.
DrawingView.OnDraw(Android.Graphics.Canvas)Called when the view should render its content.
Event processingView.OnKeyDown(Keycode, Android.Views.KeyEvent)Called when a new hardware key event occurs.
View.OnKeyUp(Keycode, Android.Views.KeyEvent)Called when a hardware key up event occurs.
View.OnTrackballEvent(MotionEvent)Called when a trackball motion event occurs.
View.OnTouchEvent(MotionEvent)Called when a touch screen motion event occurs.
FocusView.OnFocusChanged(bool, Android.Views.FocusSearchDirection, Android.Views.FocusSearchDirection)Called when the view gains or loses focus.
View.OnWindowFocusChanged(bool)Called when the window containing the view gains or loses focus.
AttachingView.OnAttachedToWindowCalled when the view is attached to a window.
View.OnDetachedFromWindowCalled when the view is detached from its window.
View.OnWindowVisibilityChanged(ViewStates)Called when the visibility of the window containing the view has changed.

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.

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 View.Left and View.Top. 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 View.Right and View.Bottom. These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling View.Right is similar to the following computation: getLeft() + getWidth() (see for more information about the width.)

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 for more details.) The measured dimensions can be obtained by calling View.MeasuredWidth and View.MeasuredHeight.

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 View.Width and View.Height.

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 View.SetPadding(int, System.Int32, System.Int32, System.Int32) or View.SetPaddingRelative(int, System.Int32, System.Int32, System.Int32) method and queried by calling View.PaddingLeft, View.PaddingTop, View.PaddingRight, View.PaddingBottom, View.PaddingStart, View.PaddingEnd.

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 Android.Views.ViewGroup and NoType:android/view/ViewGroup$MarginLayoutParams;Href=../../../reference/android/view/ViewGroup.MarginLayoutParams.html for further information.

Layout is a two pass process: a measure pass and a layout pass. The measuring pass is implemented in View.Measure(int, System.Int32) 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 View.Layout(int, System.Int32, System.Int32, System.Int32) 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 View.MeasuredWidth and View.MeasuredHeight 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 NoType:android/view/View$MeasureSpec;Href=../../../reference/android/view/View.MeasureSpec.html 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:

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:

To intiate a layout, call View.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 is handled by walking the tree and recording the drawing commands of any View that needs to update. After this, the drawing commands of the entire tree are issued to screen, clipped to the newly damaged area.

The tree is largely recorded and drawn in order, with parents drawn before (i.e., behind) their children, with siblings drawn in the order they appear in the tree. If you set a background drawable for a View, then the View will draw it before calling back to its onDraw() method. The child drawing order can be overridden with ViewGroup.ChildrenDrawingOrderEnabled in a ViewGroup, and with View.SetZ(float) custom Z values} set on Views.

To force a view to draw, call View.Invalidate.

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 View.RequestLayout.
  3. Similarly, if in the course of processing the event the view's appearance may need to be changed, the view will call View.Invalidate.
  4. If either View.RequestLayout or View.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 Android.OS.Handler.

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 View.Focusable method. To change whether a view can take focus, call View.Focusable. When in touch mode (see notes below) views indicate whether they still would like focus via View.FocusableInTouchMode and can change this via View.FocusableInTouchMode.

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:

java Example

 nextFocusDown
 nextFocusLeft
 nextFocusRight
 nextFocusUp
 

To get a particular view to take focus, call View.RequestFocus.

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 View.FocusableInTouchMode 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 Android.App.Activitys. Call View.IsInTouchMode to see whether the device is currently in touch mode.

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 View.ScrollBy(int, System.Int32), View.ScrollTo(int, System.Int32), and View.AwakenScrollBars for more details.

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.

The View class exposes an View.ALPHA property, as well as several transform-related properties, such as View.TRANSLATION_X and View.TRANSLATION_Y. These properties are available both in the Android.Util.Property form as well as in similarly-named setter/getter methods (such as View.Alpha for View.ALPHA). These properties can be used to set persistent state associated with these rendering-related properties on the view. The properties and methods can also be used in conjunction with Android.Animation.Animator-based animations, described more in the section.

Starting with Android 3.0, the preferred way of animating views is to use the Android.Animation package APIs. These Android.Animation.Animator-based classes change actual properties of the View object, such as View.Alpha and View.TranslationX. This behavior is contrasted to that of the pre-3.0 Android.Views.Animations.Animation-based classes, which instead animate only how the view is drawn on the display. In particular, the Android.Views.ViewPropertyAnimator class makes animating these View properties particularly easy and efficient.

Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. You can attach an Android.Views.Animations.Animation object to a view using View.Animation or View.StartAnimation(Android.Views.Animations.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.

Sometimes it is essential that an application be able to verify that an action is being performed with the full knowledge and consent of the user, such as granting a permission request, making a purchase or clicking on an advertisement. Unfortunately, a malicious application could try to spoof the user into performing these actions, unaware, by concealing the intended purpose of the view. As a remedy, the framework offers a touch filtering mechanism that can be used to improve the security of views that provide access to sensitive functionality.

To enable touch filtering, call View.FilterTouchesWhenObscured or set the android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework will discard touches that are received whenever the view's window is obscured by another visible window. As a result, the view will not receive touches whenever a toast, dialog or other window appears above the view's window.

For more fine-grained control over security, consider overriding the View.OnFilterTouchEventForSecurity(MotionEvent) method to implement your own security policy. See also MotionEvent.FlagWindowIsObscured.

See Also

[Android Documentation]

Requirements

Namespace: Android.Views
Assembly: Mono.Android (in Mono.Android.dll)
Assembly Versions: 0.0.0.0
Since: Added in API level 1