Summary of Common Methods for Custom Controls

Summary of Common Methods for Custom Controls

[[183466]]

In addition to the measurement, layout and drawing APIs involved in the drawing process, there are some APIs that are used frequently in custom controls. I have summarized them here, and I invite you to supplement or correct them so that I can learn more.

inflate

The inflate method is often used to parse an XML layout file and is often used in custom composite controls. The methods used include:

  1. View .inflate(context, resource, root)LayoutInflater. from (getContext()).inflate(resource, root);

View.inflate actually calls LayoutInflater to parse an xml:

  1. public   static   View inflate(Context context, int resource, ViewGroup root) {
  2.  
  3. LayoutInflater factory = LayoutInflater. from (context); return factory.inflate(resource, root);
  4.  
  5. }

So there is no difference between these two postures. Let's discuss the return value of inflate(resouce, root). The parameter resource is the layout resource, and root is the root node passed in. If root is passed in as null, inflate will parse the XML corresponding to resource and return the root node in this XML. If root is not passed in as null, inflate will parse this XML layout and add it to the root node root, and then return the root node root.

There is also an inflate method with three parameters:

  1. inflate( int resource, ViewGroup root, boolean attachToRoot)

There is an additional parameter attachToRoot here. If root is null, the root node in the parsed XML layout is returned; if root is not null, attachToRoot is true, inflate will parse the XML layout and add it to the root node root, and then return the root node root; if root is not null, attachToRoot is false, inflate will parse the XML layout but will not add it to the root node root, and then return the root node in the parsed XML layout. At this time, the role of root is only to provide layout parameter attributes for the root node in XML, because the root node in XML does not know who its parent container is, so if no one provides it, its layout parameters will become invalid.

onFinishInflate

onFinishInflate is a call after all children are resolved. For example, if we customize a ViewGroup and want to find the children to do some settings, if we use findViewById in the constructor of the custom ViewGroup, it will return null, because the children have not been resolved yet, that is, they have not been born yet. At this time, we can override onFinishInflate and find them after the children are resolved.

requestLayout

There are many introductions about requestLayout. The requestLayout() method will trigger the measure process and layout process, will not call the draw process, and will not redraw any View including the caller itself.

onSizeChange(int w, int h, int oldw, int oldh)

onSizeChange is called when the size of the control changes. Its calling trace is layout->setFrame->sizeChange->onSizeChange. It will definitely be called when the control is laid out for the first time. We can get the size of the control by overriding this method. Therefore, this method is usually used to initialize member variables related to the size of the control.

invalidate

Invalidate is used very frequently. It triggers the redrawing of the View, which is the drawing process of the drawing process, but does not call the measurement and layout process.

postInvalidate

We all know that Android's UI is a single-threaded model, and the UI can only be updated in the main thread, so we can only call invalidate in the main thread. If you want to update the UI in a child thread, you can use a handler to send a msg to the main thread, and then call invalidate when processing the msg. In addition, we can directly call postInvalidate to update the UI in the child thread. The internal implementation of postInvalidate also uses a handler to send a msg to the main thread and then call invalidate.

setWillNotDraw

Custom ViewGroups usually do not draw themselves. If you override the draw method or onDraw method in ViewGroup, you will find that they will not be called at all. However, if you set a background for your ViewGroup, you will find that the draw method and onDraw method will be called again.

We know that ViewGroup itself is a View, and its drawing is initiated by its parent container, specifically in the drawChild method in ViewGroup:

  1. protected boolean drawChild(Canvas canvas, View child, long drawingTime) { return child.draw(canvas, this, drawingTime);
  2. }

Note that the draw method here has three parameters, which is different from the draw method with one parameter that we usually talk about. Find the draw method with three parameters in the View class and find the following code:

  1. if (!hasDisplayList) { // Fast path for layouts with   no backgrounds
  2. if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
  3. mPrivateFlags &= ~PFLAG_DIRTY_MASK;
  4. dispatchDraw(canvas);
  5. } else {
  6. draw(canvas);
  7. }
  8. }

From here we can see a clue, usually a ViewGroup will skip drawing by default, that is, (mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW will return true, then it will directly use the dispatchDraw method to draw its own children, and will not call draw(canvas) with a parameter, but when the ViewGroup has a background or setWillNotDraw(false), it will use the draw(canvas) method. So if we customize a ViewGroup and want to implement its own drawing, we can set a background for it or call setWillNotDraw(false).

onAttachedToWindow

onAttachedToWindow is called when a View is bound to a window. According to the annotations on this method in the View class, onAttachedToWindow will definitely be called before the onDraw method.

In the custom control, we can register some broadcast receivers, observers or start some tasks in onAttachedToWindow. You can refer to the implementation in TextClock.

onDetachedFromWindow

onDetachedFromWindow corresponds to onAttachedToWindow, which is a call when a View is removed from a window. If some listeners are registered in onAttachedWindow, they are usually unregistered in onDetachedFromWindow.

ViewTreeObserver

ViewTreeObserver is an observer of the view tree, monitoring some global changes of the view tree, including the layout of the entire view tree, starting drawing, changes in touch mode, etc. We cannot directly initialize the object of ViewTreeObserver, but need to obtain it through getViewTreeObserver().

ViewTreeObserver.OnGlobalLayoutListener

When the global layout in a view tree changes or the visual state of a view in the view tree changes, the general usage posture of the listener is:

  1. getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override
  2. public void onGlobalLayout() {
  3. getViewTreeObserver().removeGlobalOnLayoutListener(this); //do something you like  
  4. // for example, get view width or height height
  5. }
  6. });

ViewTreeObserver.OnPreDrawListener

When a view tree is about to be drawn, the general usage posture is:

  1. getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() { @Override
  2. public boolean onPreDraw() { //do something before draw
  3. // for example, request a new layout
  4. return   true ;
  5. }
  6. });

<<:  The third episode of the Aiti tribe consultation: Analysis of Python's advantages in big data processing

>>:  MVP Pattern in Android (with Examples)

Recommend

Behind the popularity of Xiaohongshu, how is the community operated?

Half a month ago, Xiaohongshu announced the compl...

Boiling tea around the fire, someone got infected

When the weather gets cold “Tea brewing around th...

IDC: Enterprise WLAN market to decline 12.7% year-over-year in 2024

The global enterprise wireless LAN (WLAN) market ...

Experience and skills in writing e-commerce marketing plans!

Everyone in the e-commerce industry knows that th...

Wuwei Classroom Novice Trading Practice Class "Trading Indicators"

Introduction to the resources of "Trading In...

Why have all the top Tik Tok anchors stopped broadcasting?

The number one female anchor of TikTok @朱瓜瓜 has s...

Analyzing Google’s competitive advertising strategy!

If you have ever done keyword search advertising ...

UBS: Apple's dominance in China is over

Recently, UBS released a report saying that the p...

Zhao Dongxuan: "50 Strategies for Traffic as King" 50 episodes

Zhao Dongxuan: "50 Strategies for Traffic is ...