Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Android customizes View

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to customize View for Android. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

First of all, let me talk about the control architecture of Android. Android controls can be divided into two categories, ViewGroup and View. You can include multiple View in ViewGroup and manage them. The control tree is composed of these two parts, and the upper layer of the control tree is responsible for the drawing, measurement and interaction of the lower-level controls. The findViewById () method we use in Activity searches for the corresponding ID in the control tree using depth traversal. At the top of each control tree, there is a ViewParent object, which is the core of the whole tree and is responsible for scheduling all interactive events. In Activity, we use setContentView () to load the layout. Each Activity contains a Window object, usually PhoneWindow in Android, which takes a DecorView as the root View of the entire window and renders what is to be displayed on the window. DecorView is divided into two parts, one is TitleView, the other is ContentView. ContentView is a Framelayout whose ID is content, in which the layout file is set. And TitleView is when we see the topbar title bar. This is the process by which activity loads the layout file.

Next, we start to talk about the use of custom controls, which will be used with some theoretical analysis. Custom controls can be divided into three types, one is to expand the system controls provided by Google to achieve the desired effect. One is to combine the controls provided by the system and use them as a composite control. Another is to redraw and measure a completely new control.

First, expand the system controls provided by Google

If we want to extend the Textview control, first we need to define a class that inherits TextView and selectively overrides its onDraw (), onMeasure (), onTouchEvent (), and other methods. Among them, onDraw () is responsible for drawing the image, onMeasure () is responsible for measuring the position, and onTouchEvent () is responsible for setting touch events. When we want to directly draw a TextView with a background color, we can define a brush in the class and paint in onDraw (). The code is as follows:

Paint paint1=new Paint (); / / define brush paint1.setColor (Color.YELLOW); paint1.setStyle (Paint.Style.FILL)

Then, through the following code, you can draw a Textview with a rectangle, but you need to call the onDraw () of the parent class after the drawing is completed, because it is extended on the system control, so it also has its original function.

@ Override protected void onDraw (Canvas canvas) {canvas.drawRect (0Magne0Pol) getmeasuredWidth (), getMeasuredHeight (), paint1); / / draw a rectangle canvas.save (); super.onDraw (canvas); canvas.restore ();}

You can use the canvas object to draw, and I will explain canvas in the next blog post.

Then, we only need to add custom controls to the layout file. In the layout file, the name of the custom view is the package name of the custom control class plus the class name. Suppose that the CustomTextview class inherits TextView. The example is as follows:

Second, combine the controls provided by the system

In addition to expanding the existing controls, we can also combine the controls into a new control to use. First, let's define a new layout file and add Imageview and Textview. The code is as follows.

Then we define a class that inherits LinearLayout and initializes the control and layout in the constructor of the class.

Public void init (Context context) {/ / specify the display mode of the linear layout, vertical setOrientation (VERTICAL); / / set the layout method expected by the user LayoutParams mLayoutParams = new LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); setLayoutParams (mLayoutParams); setGravity (Gravity.CENTER); setPadding (4,4,4,4); / / set its layout file View mButtonbtnView = LayoutInflater.from (context) .comparate (layout.botton_btn_view, this, true) MImageView = mButtonbtnView.findViewById (id.iv); mTextView = mButtonbtnView.findViewById (id.tv);}

Next, it is used in the same way as expanding controls, by adding controls directly to the layout file.

Third, rewrite View to implement brand-new controls.

When the native controls of the system can not meet our needs, we can define a new control to complete the required functions. To create a new control, you need to inherit the View class, and the difficulty lies in drawing the control and implementing interaction. When inheriting the View class, we also need to override its onDraw (), onMeasure (), onTouchEvent () to implement drawing, measuring, and touching events.

OnDraw () drawing is to draw the shape of the control by calling a series of methods in the canvas object.

OnMeasure ()

Next, let me talk about onMeasure (). Before drawing a View, we need to tell the system how big a View we need to draw and its location, and that's what onMeasure () does. First, let's take a look at the three modes of measurement:

EXACTLY: precise value mode, which is used when specifying a specific value for view.

AT_MOST: maximum mode, used to set the control to "wrap_content", which varies depending on the child control or content.

UNSPECIFIED: the drawing control can be as big as you want.

According to the above three modes, we can judge and use them when measuring. First, we rewrite an onMeasure () method for view. Then get the measurement mode of the control by using the MeasureSpec class. MeasureSpec uses bit operations, with the highest 2 bits for the measurement mode and the remaining 30 bits for the size of the measurement.

Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {int widthMode = MeasureSpec.getMode (widthMeasureSpec); int widthSize = MeasureSpec.getSize (widthMeasureSpec); if (widthMode = = MeasureSpec.EXACTLY) {} else if (widthMode = = MeasureSpec.AT_MOST) {} else if (widthMode = = MeasureSpec.UNSPECIFIED) {}}

The above code is to define the size of the control by judging the measurement mode. Here only the width of the control is measured, and the measurement of the height of the control is similar, so it is not explained in detail.

As mentioned earlier, ViewGroup is used to manage controls, and when the size of ViewGroup is "wrap_content", it iterates through all its child View to get the size of the child View, and then sets its own size. Layouts we have used, such as RelativeLayout,LinearLayout, inherit from ViewGroup, so they also use this method to get their own size.

OnTouchEvent ()

OnTouchEvent () is what we call the touch event, because the Android phone is a touch screen, so we customize the View when touching the screen, we also need to have some processing to complete the interaction. When you override the onTouchEvent method, you can see the object that needs to be passed in to MotionEvent. We can set the touch event through this class, and we can also get the location of the touch point. We can use getAction () to get the action of the touch event to determine whether to press the screen or move. In the Android coordinate system, we all know that when the Android screen is vertical, it takes the position of the upper left corner as the origin, the positive direction of the x axis to the right, and the positive direction of the y axis downward. After knowing this, we can complete some interactive operations by calling the getX () and getY () methods to obtain the coordinates of the touch point.

Public boolean onTouchEvent (MotionEvent event) {float x; switch (event.getAction ()) {case MotionEvent.ACTION_DOWN: {x=event.getX ();} break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: break;} return true;}

These are the common rewriting methods for custom controls, and by rewriting these methods, we can basically achieve a simple custom control. Next, let's take a look at the principle of the control's event interception mechanism.

Analysis of event interception Mechanism

As we mentioned earlier, the control structure is a tree structure, and there may be multiple ViewGroup or View in a ViewGroup, so how exactly are touch events assigned to each View and ViewGroup? Let's assume that there is a ViewGroupA with a ViewGroupB nested inside it, and a View nested inside the ViewGroupB. When we rewrite the ViewGroupA class, we need to rewrite these three methods:

DispatchTouchEvent () onInterceptTouchEvent () onTouchEvent ()

When rewriting View, you need to rewrite two methods:

DispatchTouchEvent () onTouchEvent ()

As you can see from the name, there are more onInterceptTouchEvent () methods in ViewGroup than View, which is the core of event interception. When you Log and click View in each method, you will find the order of the method calls:

First, the dispatchTouchEvent () and onInterceptTouchEvent () of the ViewGroupA class are called.

Then the dispatchTouchEvent () and onInterceptTouchEvent () of the ViewGroupB class are called.

Then go to the dispatchTouchEvent () method of View.

The order of this call is the order in which events are delivered, and the order in which events are handled is:

OnTouchEvent () for View. OnTouchEvent () for ViewGroupB. OnTouchEvent () for ViewGroupA.

From this, it can be seen that the distribution of events is published by the upper ViewGroup, and then sent layer by layer. On the other hand, the handling of the event is handled by the lower-level View, and then uploaded layer by layer. As mentioned earlier, onInterceptTouchEvent () is the core of event interception, so as long as you set its return value to true, you can intercept the event so that it is no longer sent, while onTouchEvent () returns false, and the event will not be uploaded after handling. The process of event distribution and interception is roughly explained.

This is the end of this article on "how to customize Android View". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report