android.view.View详解

View实现3个接口

Drawable.Callback

  • public void invalidateDrawable(Drawable who);
  • public void scheduleDrawable(Drawable who, Runnable what, long when);
  • public void unscheduleDrawable(Drawable who, Runnable what);

KeyEvent.Callback

  • boolean onKeyDown(int keyCode, KeyEvent event);
  • boolean onKeyLongPress(int keyCode, KeyEvent event);
  • boolean onKeyUp(int keyCode, KeyEvent event);
  • boolean onKeyMultiple(int keyCode, int count, KeyEvent event);

AccessibilityEventSource

  • public void sendAccessibilityEvent(int eventType);
  • public void sendAccessibilityEventUnchecked(AccessibilityEvent event);

类View中以on开头的方法

  1. protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect)
  2. public void onStartTemporaryDetach()
  3. public void onFinishTemporaryDetach()
  4. public void onWindowFocusChanged(boolean hasWindowFocus)
  5. protected void onVisibilityChanged(View changedView, int visibility)
  6. protected void onDisplayHint(int hint)
  7. protected void onWindowVisibilityChanged(int visibility)
  8. protected void onConfigurationChanged(Configuration newConfig)
  9. public boolean onKeyPreIme(int keyCode, KeyEvent event)
  10. public boolean onKeyDown(int keyCode, KeyEvent event)
  11. public boolean onKeyLongPress(int keyCode, KeyEvent event)
  12. public boolean onKeyUp(int keyCode, KeyEvent event)
  13. public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
  14. public boolean onKeyShortcut(int keyCode, KeyEvent event)
  15. public boolean onCheckIsTextEditor()
  16. public InputConnection onCreateInputConnection(EditorInfo outAttrs)
  17. protected void onCreateContextMenu(ContextMenu menu)
  18. public boolean onTrackballEvent(MotionEvent event)
  19. public boolean onTouchEvent(MotionEvent event)
  20. protected void onScrollChanged(int l, int t, int oldl, int oldt)
  21. protected void onSizeChanged(int w, int h, int oldw, int oldh)
  22. protected final void onDrawScrollBars(Canvas canvas)
  23. protected void onDraw(Canvas canvas)
  24. protected void onAttachedToWindow()
  25. protected void onDetachedFromWindow()
  26. protected Parcelable onSaveInstanceState()
  27. protected void onRestoreInstanceState(Parcelable state)
  28. protected void onLayout(boolean changed, int left, int top, int right, int bottom)
  29. protected void onFinishInflate()
  30. protected int[] onCreateDrawableState(int extraSpace)
  31. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
  32. protected void onAnimationStart()
  33. protected void onAnimationEnd()
  34. protected boolean onSetAlpha(int alpha)

Overview

  • 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 ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views (or other ViewGroups) and define their layout properties.

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).

1. 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.

2. 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.

3. Drawing

onDraw(Canvas)

  • Called when the view should render its content. 

4. 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.  

5. 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.  

6. 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.
  • 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()

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.
  • 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
    • MATCH_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.




原文地址:https://www.cnblogs.com/fengzhblog/p/2786405.html