Overview
Android has given us a lot of view for us to use, but there may be times when these components don't meet our needs, and then we need to customize the controls. Custom controls always feel like a complex technique for beginners. Because it involves more knowledge points. But any complex technology behind it is a little bit of the accumulation of simple knowledge. Learning from custom controls is a great way to learn more about Android, so it is necessary to study Android custom controls. Remember the previous study is always thinking to understand a lot of knowledge points, and then learn to customize the control, but every time you write custom control, always do not know where to start. Later in the process of learning to find yourself followed by writing some simple custom controls, and then in the process encountered a lack of knowledge to learn. The ability to customize controls has improved. Other knowledge has also been well consolidated and understood. So, what I wrote today is how to customize a control. Rather than the refinement of the knowledge points involved. A thing we know how to use first, then ask why.
Points to consider for custom controls
Based on the introduction of the Android Developers website, you need the following steps to customize the control. (Some steps can be omitted, depending on your needs)
1. Create VIEW2, Process view Layout 3, Draw View4, interact with user 5, optimize defined view
The five items listed above are the steps of the custom control given by Android. Each step contains a lot of small points of knowledge. We can remember these five points and understand the small points of knowledge contained in each point. Plus some exercises for custom controls. Keep this knowledge in mind and believe that each of us is able to define excellent custom controls. Next, we'll start with a detailed explanation of the 5 points listed above
Custom Controls 5 Essentials detailed description 1, create view inherit view
Some of the friends who know about Android know that many of the view that Android offers us is inherited and view. So our custom view is also inherited from view, of course, if you want to customize the view that has the functionality of some of the controls that Android has already provided, you can directly inherit from the controls already provided.
When we were using the controls provided by Android, we edited a control in the. xml file and was able to see and get the control when it was run. Our custom controls, of course, also support configuration and some custom properties, so the following construction methods must be available. This construction method allows us to create and edit instances of our custom controls in the. xml file.
It says so much actually is the following piece of code.
class PieChart extends View {//继承View public PieChart(Context context, AttributeSet attrs) { super(context, attrs); }//为了支持.xml中进行创建和编辑}
Defining Custom Properties
Most of the time, our custom view needs more flexibility, such as the ability to specify a color size in the XML, and the control to show its color and size when the program is running. So we need custom attributes
Custom properties are usually written in the Res/values/attrs.xml file below is the standard notation for custom attributes
<declare-styleable name="Piechart"> <attr name="Showtext" format="boolean" /> <attr name="labelposition" format="enum"> <enum name="Left" value="0"/> <enum name="Right" value="1"/> </attr> </declare-styleable>
This code declares two custom properties, Showtext and LabelPosition, which belong to Styleable Piechart, and for convenience, the general styleable name is the same as the class name of our custom control. After the custom control is defined, it is used.
Working with code samples
<?xml version= "1.0" encoding= "Utf-8"? <linearlayout xmlns:android = "Http://schemas.android.com/apk/res /android " xmlns:custom =" HTTP +/ Schemas.android.com/apk/res/com.example.customviews "; <com.example.customviews.charting.piechart custom:showText = custom:labelposition = "left" /> </linearlayout ;
You need to specify a namespace when using a custom attribute, and a fixed notation is to http://schemas.android.com/apk/res/your package name. If you are in Android studio, you can also use Http://schemas.android.com/apk/res/res-auto
Get Custom properties
With the control custom property set in the XML, we need to get the property to do something about it. Otherwise, there is no point in defining a custom property.
The fixed get custom property code is as follows
Public Piechart (context context, AttributeSet Attrs) {Super (context, attrs);TypedArray A = Context. Gettheme(). Obtainstyledattributes(Attrs, R. Styleable. Piechart,0,0);try {mshowtext = a. Getboolean(R. Styleable. Piechart_showtext, False);Mtextpos = A. Getinteger(R. Styleable. Piechart_labelposition,0);} finally {a. Recycle();}}
When we create a view in XML, all attributes declared in the XML are passed into the parameters of the AttributeSet type in the view's construction method.
Returns a Typedarray object by calling the Obtainstyledattributes () method of the context. The value of the custom property is then obtained directly from the Typedarray object.
Because the Typedarray object is a shared resource, you must call the Recycle () method to reclaim after the value has been obtained.
To add a Set property event
Custom attributes specified in XML are only available when view is initialized, and sometimes we may do something at runtime, which requires that we set getter and setter methods for custom properties, and the following code shows the set and get methods exposed by custom controls
publicbooleanisShowText() { return mShowText;}publicvoidsetShowText(boolean showText) { mShowText = showText; invalidate(); requestLayout();}
Focus on the Setshowtext method, after assigning a value to the Mshowtext, the Invalidate () and Requestlayout () methods are called, and when our custom control's properties change, the control's appearance can change. In this case, you need to call the invalidate () method to let the system call the view's OnDraw () redraw. Similarly, changes in control properties can cause changes in the size and shape of the control, so we need to call Requestlayout () to request a measurement to get a new layout position.
2. Handle the layout of the view. Measurement
A view is always the width and height of the display, and the measurement view is designed so that the custom control can be displayed with the right width and height according to the different situations. The Onmeasure method must be mentioned when referring to measurements. The Onmeasure method is a view that determines its wide height.
@Override protectedvoidonMeasure(intint heightMeasureSpec) { }
There are two important parameters in the Onmeasure method, Widthmeasurespec, Heightmeasurespec. All you need to remember here is that they contain two messages: mode and size
We can get the mode and size by the following code
int specMode = MeasureSpec.getMode(measureSpec);int specSize = MeasureSpec.getSize(measureSpec);
So what does the acquired mode and size represent?
Mode represents the parent control of our current control that tells us the control, and how you should lay it out.
Mode has three selectable values: Exactly, At_most, UNSPECIFIED. What they mean is:
Exactly: The parent control tells us that the child controls have a certain size that you can lay out by this size. For example, we specify a certain DP value and a macth_parent condition.
At_most: The current control cannot exceed a fixed maximum value, which is typically wrap_content.
UNSPECIFIED: There is no limit to the current control, how big it is, and this rarely happens.
Size is actually a size that the parent layout passes over, and the parent layout wants the current layout size.
Here is a fixed pseudo-code rewrite onmeasure:
ifis EXACTLY{ 父布局已经告诉了我们当前布局应该是多大的宽高, 所以我们直接返回从measureSpec中获取到的size }else{ 计算出希望的desiredSize ifis AT_MOST 返回desireSize和specSize当中的最小值 else: 返回计算出的desireSize}
Although the above code is basically fixed, but the steps need to write a bit more, if you do not want to write your own, you can also use Android to provide us with the tool method: Resolvesizeandstate, this method needs to pass in two parameters: we measure the size and the parent layout want size, It returns the correct size according to various conditions. So that we can not implement the above template, just calculate the desired size and then call Resolvesizeandstate. Then I'll show you how to use this method to determine the size of the view when I do a custom view.
Do not forget to call the Setmeasureddimension () method in onmeasure after calculating the height and width. Otherwise, a run-time exception occurs.
Calculate the values required for some custom controls Onsizechange ()
The Onsizechange () method is called when the view has been assigned a size value for the first time, or if the size of the view has changed. So it is generally used to calculate some positions and values related to the size of the view.
3. Draw the view (draw)
Once the custom control is created and the measurement code is written, you can then implement OnDraw () to draw the view, the OnDraw method contains a canvas called the canvas parameters, OnDraw () simply say two points:
Canvas decides what to draw.
Paint decides how to draw
For example, Canvas provides a way to draw a line, and paint determines the color of the line. Canvas provides a drawing rectangle, and the paint can decide whether to make the rectangle hollow or solid.
Before you start drawing in the OnDraw method, you should initialize the information for the brush paint object. This is because the redraw of the view is more frequent, and it is possible to call OnDraw multiple times, so the initialized code should not be placed in the OnDraw method.
Many of the methods provided by canvas and paint are not listed in this article. You can look at the API on your own, and we'll use it later in the article, and now you just need to understand the general steps of the definition and then work on it to deepen your understanding.
4. Interacting with the user
In some cases, your custom control needs to do more than just display a nice piece of content, but also support user clicks, drags, and so on, and our custom controls need to do the user interaction step.
The most common event in the Android system is the touch event, which invokes the view's Ontouchevent (android.view.MotionEvent). Override this method to handle our event logic
@Override publicbooleanonTouchEvent(MotionEvent event) { returnsuper.onTouchEvent(event); }
To the Ontouchevent method believe that everyone has a certain understanding, if you do not understand, you first remember this is to deal with the touch of the place.
Now the touch has more gestures, such as tap, swipe, and so on, so you need to use Android-provided gesturedetector to support special user interactions. You only need to implement the corresponding interface in the Gesturedetector and handle the corresponding callback method.
In addition to gestures, we need to make the sliding animation appear smoother if there is a move or something. The animation should be smooth start and end, rather than suddenly disappear suddenly start. In this case, we need to use the Properties Animation property animation Framework
Since there are more examples of knowledge involved in interacting with the user, I'll explain it later in the custom control article.
5. Optimize your custom view
After the above steps are finished, a complete custom control is in fact out. The next thing you need to do is make sure your custom controls run smoothly, officially: to avoid slowing your controls, make sure that the animation stays at 60 frames per second.
The following are the recommendations of the website for optimization:
1. Avoid unnecessary code
2. There should be no code that causes garbage collection in the OnDraw () method.
3. Make the OnDraw () method call as few as possible, and most OnDraw () method calls are the result of a manual call to invalidate (), so do not call the Invalidate () method if you do not have to.
Summarize
Basically, the general steps of customizing the controls and the knowledge points that may be involved are all done. Look at a picture.
The picture basically describes the general flow of the custom control, and to the right is some of the points of knowledge involved in the relative process. You can see that the custom controls include a lot of Android knowledge. So it is necessary to learn Android custom controls. When you can easily define a perfect custom control, I believe you are already Daniel.
This article provides a general overview of the steps of a custom control, and if you are unclear about the custom process, remember the steps mentioned above, at least with an approximate impression. In the following article, I followed this step to explain some of the custom controls, using the steps listed here to step through the custom controls we want.
If the article has the wrong place also please comment, read the article by the way to make a comment under the praise! Thank you.
Learn Android Custom Controls 1