Android drawing mechanism (i) View class

Source: Internet
Author: User

Understanding of the Android mapping mechanism is critical in Android learning, including custom controls and very frequent use of content. Recently encountered a difficult problem in the project, several modules of the project are used in the ListView or the GridView "drop-down refresh, pull load more" function. At the beginning of the Internet to find the works of Daniel, used in the project later found that there will be a sticky phenomenon, improvement will be improved, but still feel a lack of. Helpless I am a Virgo rookie, try to find out the root cause of these problems but found not to start, so first fill the foundation. (Plain text looks really laborious, so by the way other articles)

Overview

The view class represents the basic creation block of the UI component. A view view occupies a rectangular area of the screen and is responsible for drawing and event handling. The view class is the base class for basic controls for creating UI components (such as button buttons, text field TextView, and so on). The view group ViewGroup class is the base class for the layout class, and the layout class is a non-visible container for loading other views (or other viewgroup) and declaring their properties.

(This rectangle has no bounds, can refer to http://www.open-open.com/lib/view/open1328834050046.html)

Development Guide

For information about creating a UI component reference documentation, you can read the Developer Guide for user interface in the documentation.

Working with views

All views in the form are arranged in a separate view tree. You can add views in hard-coded form, or specify a view tree in one or more XML files. Android has provided many unique view subclasses by default for displaying text, images, or other content. Once you create a view tree, you will be able to perform the following series of classic actions:

* Set properties: For example, set the text for TextView. The available properties and methods may vary in the control view, and it is important to note that properties that are visible at the time of creation are typically set in the XML layout file.
* Set Focus: The Android framework handles moving focus in response to user input, and you can call Requesfocus () if you want to force the focus to be set.
* Set Listener: The view allows the client to set the listener, which is notified when related events occur on the view. For example, allows you to set a listener for the view to get focus gain and loss notifications. You can register the focus listener via Setonfocuschangelistener (Android.view.View.OnFocusChangeListener). Other view subclasses may provide more specific listeners. For example, a button exposes a listener that is used to notify the button of a click event

Note: The Android framework is responsible for measuring, layout, and drawing views (these three processes are not the same). You should not actively invoke the method that completes these actions in the view unless you implement the ViewGroup.

Custom Controls

To create a custom view, you often need to provide some standard methods of rewriting that the framework calls on all views. However, there is no need to rewrite all the methods, or even just rewrite OnDraw (Android.graphics.Canvas).

Category Methods Description
Creation Constructors There is a form of the constructor that was called when the view was created from code and a form that was called when the V Iew is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file.
Contains the arrangement of a constructor, which is called when the view is created by hard-coded or inflate mode. The second table arrangement parses and applies the properties of the layout file.
onFinishInflate() Called after a view and all of its children have been inflated from XML.
Called when a view and all its child views are finished inflate from the layout file.
Layout onMeasure(int, int) Called to determine the size requirements for this view and all of its children.
Calling this method determines the size specification of a view and all its child views.
onLayout(boolean, int, int, int, int) Called when the This view should assign a size and position to all of its children.
Called when a view is assigned a dimension or position to all its subclasses.
onSizeChanged(int, int, int, int) Called when the size of this view has changed.
Called when the dimension of the view changes.
Drawing onDraw(android.graphics.Canvas) Called when the view should render (rendering) its content.
Called when the view needs to render his content
Event processing onKeyDown(int, KeyEvent) Called when a new hardware key event occurs.
Called when a new hardware press event occurs
onKeyUp(int, KeyEvent) Called when a hardware key up event occurs.
When on a hardware
onTrackballEvent(MotionEvent) Called when a trackball motion (trackball Movement) event occurs.
Called when a trackball event occurs
onTouchEvent(MotionEvent) Called when a touch screen motion event occurs.
Called when a touch-screen event occurs
Focus onFocusChanged(boolean, int, android.graphics.Rect) Called when the view gains or loses focus.
Called when the view Gets or loses focus
onWindowFocusChanged(boolean) Called when the window containing the view gains or loses focus.
Called when the window that contains the view loses or gets focus

Attaching onAttachedToWindow() Called when the view was attached to a window.
Called when the view is attached to the screen
onDetachedFromWindow() Called when the view was detached from its window.
Called when the view is detached from the screen
onWindowVisibilityChanged(int) Called when the visibility of the window containing the view had changed.
Called when the window that contains the view changes


IDs

A view can be associated with an integer ID, which is typically defined in a layout file and used to look for a specified view in a tree of views. The ID requirements for views are unique across the entire view tree, but it is best to make sure that they are unique at least in the view tree that you are searching.



location

The geometry of the view is a rectangle. The view has a position, represented by left and top coordinate pairs and a wide height dimension. The units of the position are pixels. by calling GetLeft (), the GetTop () method can retrieve the location of the view. The former returns the left or x coordinate of the view rectangle. The latter returns the coordinates of the top or y axes. Both methods return a position relative to their parent class. For example, when call GetLeft () returns 20 o'clock, this view is located at the right 20 pixels from the left edge of the parent class.
In addition, there are some quick methods that are provided to avoid unnecessary computations, both getright () and Getbottom (). This method returns the coordinates of the right and bottom edges of the view rectangle. For example, calling the GetRight () method is equivalent to calculating: GetLeft () +getwidth (). (You can view the contents of the size section of the document for more information about width).

Size,padding,margins

The dimensions of the view are expressed by width and height. A view actually has a two-to-wide height value. The first pair is the measurement height and the measuring width. This set of dimension definitions affirms how much space they want to get in the parent container (you can see the layout class layouts for more details), and the measurement dimensions can be obtained by calling Getmeasureheight () and Gemeasurewidth (). The second pair is usually spoken wide and high, or is called the drawing width and drawing height. These dimensions indicate the actual size of the view when it is drawn on the screen and after the layout. The size of the measurement size and the size of the drawing may be different. The width and height can be obtained by calling GetWidth () and GetHeight (). When measuring dimensions, the view calculates the padding. The padding value is expressed by Left,top,right,bottom, which sets the offset at which padding can be used to specify the view content. For example, setting the left inner Edge (leftpadding) to 2 pixels offsets the view content from left to right by 2 pixels. Can be set by calling setpadding (int, int, int, int) or setpaddingrelative (int, int, int, int), and by Getpaddingleft (), Getpaddingtop () , Getpaddingright (), Getpaddingbottom (), Getpaddingstart (), getpaddingend () query. The view supports hard-coded setting of an inner edge padding, but does not support hard-coded margin setting. However, the view group ViewGroup provides the appropriate way. You can view ViewGroup's viewgroup.marginlayoutparam for more information.

Layout

The layout process consists of two stages. Measurement stages and layout stages. The measurement phase is done in measure (int, int) and is a deep traversal process from top to bottom of the view tree. Each view passes its dimension rules down in the recursive phase. At the end of the measurement phase, each view holds its own measurement rules. The second stage occurs in layout (int, int), and also from top to bottom. During this pass, each parent class will place its child views according to the dimensions calculated during the measurement process.
When a view's measure (Int,int) method returns, its getmeasurewidth () and getmeasureheight () must be set, and then all descendant views of that view. The measured dimensions of a view must conform to the constraints exposed by its parent view. This ensures that at the end of the measurement process, all parent views can accept the dimension rules for all of their child views. A view may invoke the measure () method more than once in its child view, such as the parent view may find their size based on ambiguous dimensional rule measurements, and the view will call the measure () method again based on the actual value if the unrestricted dimensions of all the child views are too large or too small.

The measurement transfer process uses two class expression dimensions, the View.measurespec class is used to tell the parent view how they want to be drawn and placed, and the Layoutparam base class is used to describe how much they want their width and height.

The optional values for the dimension rule are one of the following:
* An exact value
* Match_parent, indicating that the view wants to be the same size as its view (minus the parent view's padding)
* Wrap_content, indicating that the view size is sufficient to load its contents (plus padding)
For different viewgroup subclasses, there are different layoutparam subclasses, for example, Absolutelayout has a layoutparams subclass that contains X-values and Y-values

The measurespect is used to pass layout requirements down from the parent class to the subclass, with the optional values:

UNSPECIFIED: The parent view is used to determine the dimensions that the subtree wants to get, for example, LinearLayout may call the measure () of the child view, and set its height to UNSPECIFIED width to exactly 240 to find the child view heights and the given height.
Exactly: The parent view is used to set an exact size for the child view. The child view must use this dimension and ensure that all its descendants apply to this dimension.
At_most: The parent view is used to set a maximum size for a child view, and all subclasses must ensure that their child views are appropriate for this dimension.
Create a layout by calling the Requestlayout () method, which is usually called by a view itself, and is invoked in cases where it is no longer applicable to the current boundary.

Drawing

The drawing process is done by traversing the view tree and rendering each view within the active area. Because the view tree is traversed in an orderly way, this means that the parent view is drawn before the child view, then the sibling view (the View tree depth-first traversal) that appears in turn, and the view draws the background image for you before the callback OnDraw () if the background picture is set for the view.
Note: The framework does not draw views within an invalid area, forcing the view to redraw to call the Invalidate () method.

Event handling and threading
The basic cycle of the view is as follows:
1. Time enters and is passed to the appropriate view, the view handles the processing of the event and notifies the relevant listener.
2. If you are in the process of handling an event, the boundary of the view may need to be changed, and the view will call Requestlayout ().
3. Similarly, if the appearance of the corresponding view changes during the processing of the event, the view calls invalidate ().
4. If neither requestlayout () or invalidate () is called, then the framework is responsible for measuring, laying out, and drawing the appropriate values for the view.
Note: The entire view tree is single-threaded, you must invoke any method of the view in the UI thread, and if you want to work in another view and try to update the state of the view from that thread, you should use handler.

Touch Screen mode

When a user navigates a control through the arrow keys, it is necessary to give the focus to the control that can respond to the action so that the user can see what is entered. If a device can accept a touch event, and the user interacts with it by touching the control or giving it focus, the control may not always be highlighted, and the touch screen mode is triggered.
For touch-screen devices, once the user touches the screen, the device enters touchscreen mode. From this point, only the Isfocusableintouchmode () value of the view can be used to get the focus, such as the EditText control, and other touchscreen views do not get focus when touched, such as a button. They will trigger a click listener.
At any time, when the user taps the arrow key, the view device exits touch mode and finds a view takeover focus, so the user can resume interaction with the control without touching the screen.
The touchscreen state is maintained by the activity and can be viewed by calling Isintouchmode () to see if the device is currently in touch mode.

Animation

Starting with Android3.0, the preferred way to animate a view is to use the API under the Android.animation package, which animator-based classes change the actual properties of the view object, such as transparency and x-axis translation, These actions are relative to the animation based on the previous 3.0, the previous animation class just determines how the view is drawn on the screen, and the Viewpropertyanimator class makes the animation of the view faster and more efficient.
However, you can also use the animation class before android3.0 to determine how the view should be rendered. You can pass setanimation (Animation) or startanimation (Animation). Attaches a animation object to the view. Animations can change the size, rotation, displacement, and transparency of the view over time. If the animation is used in a view with a child view, the animation affects the entire child view tree of the View node. After the animation begins, the drawing frame is responsible for redrawing the view until the animation is complete.

Scrolling
The framework provides basic support for views, 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.
The view framework provides basic support for the view to be able to move their content, including the trajectory of the packet to eat the sliding offset of the x and Y axes, as well as the mechanism for drawing the slider bar. Please see Scrollby (int, int),
ScrollTo (int, int), and awakenscrollbars () see more information.

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

Properties
The View class exposes an ALPHA property, as well as several transform-related properties, such as Translation_x Andtransl Ation_y. These properties is available both in the property form as well as in similarly-named setter/getter methods (such as SetA Lpha (float) for ALPHA). These properties can used to set persistent state associated with these rendering-related properties on the view. The properties and methods can also is used in conjunction with animator-based animations, described + in the Animation Section.

Security
Sometimes it is essential, that's application be able to verify, that's an action are 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 (malicious) application could try to spoof (spoofing) the user into performing these actions, unaware, by con Cealing (disguise) The intended purpose of the view. As a remedy (remediation), the framework offers a touch filtering mechanism that can is used to improve the security of views that P Rovide access to sensitive functionality.
To enable touch filtering, call Setfiltertoucheswhenobscured (Boolean) or set the android:filtertoucheswhenobscured Layout attribute to True. When enabled, the framework would discard touches that was received whenever the view ' s window is obscured by another visib Le window. As a result, the view won't 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 Onfiltertoucheventforsecurity (motionevent) method to Implement your own security policy. See also flag_window_is_obscured.
(Touch-filtering mechanism to mask touch events when a window-related component such as Toast,dialog,popupwindow appears)

Android drawing mechanism (i) View class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.