Learn Android custom controls together

Source: Internet
Author: User

Learn Android custom controls together
Overview

Android has provided us with a large number of views for our use, but sometimes these components may not meet our needs, at this time we need custom controls. Custom Controls are a complex technique for beginners. It involves a lot of knowledge points. However, any complicated technology is followed by a little bit of simple knowledge. By learning custom controls, you can gain a deeper understanding of android-related knowledge points. Therefore, it is necessary to learn android custom controls. I remember that I always wanted to understand a lot of knowledge before learning custom controls, but I never knew where to start every time I wrote custom controls. Later, I learned how to write some simple custom controls, and then I learned what I did not know in the process. This not only improves the ability of custom controls. Other knowledge has been well consolidated and recognized. So what I wrote today is how to customize a control. Instead of the detailed knowledge points involved in it. We know how to use one thing, and then ask why.

Considerations for Custom Controls

According to the official website of Android Developers, the following steps are required for custom controls. (According to your needs, some steps can be omitted)

1. Create View2, process View layout 3. Draw View4 and interact with users 5. Optimize the defined View

The five items listed above are the steps for customizing controls officially provided by android. Each step contains many small knowledge points. We can remember these five points and understand the small knowledge points contained in each point. Add some exercises for custom controls. I am constantly familiar with this knowledge and believe that each of us can define good custom controls. Next, we will give a detailed explanation of the five points listed above.

5 key points for custom controls 1. Creating a View inherits the View

Anyone who knows about Android knows that many views provided by android are inherited and viewed. Therefore, the custom View also inherits from the View. Of course, if you want to customize the View to have some functions of the controls already provided by android, you can directly inherit from the provided controls.

When using the control provided by android, We edited a control in the. xml file to view and obtain the control during running. Custom controls must also support configuration and some custom attributes. Therefore, the following constructor is required. This constructor allows us to create and edit an instance of our custom control in the. xml file.

As mentioned above, it is actually the following code.

Class PieChart extends View {// inherits the View public PieChart (Context context, AttributeSet attrs) {super (context, attrs);} // to support creation and editing in. xml}
Custom Attributes

In most cases, our custom View requires more flexibility. For example, if we specify the color and size attributes in xml, the control can display the corresponding color and size when the program is running. Therefore, we need to customize attributes.

Custom Attributes are usually written in the res/values/attrs. xml file. The following is the standard syntax of custom attributes.

 
                           
              
             
  

This Code declares two custom attributes, showText and labelPosition. They all belong to styleable PieChart. For convenience, the name of styleable is the same as the class name of our custom control. After the custom control is defined, it is used.
Sample Code

 
  Get Custom Attributes

When the custom properties of controls are set in xml, we need to get the properties to do something. Otherwise, custom attributes are meaningless.
The fixed code for getting custom attributes 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 xml will be passed into the AttributeSet type parameter in the view constructor.
Call the obtainStyledAttributes () method of Context to return a TypedArray object. Then, you can directly use the TypedArray object to obtain the value of the custom attribute.
Because the TypedArray object is a shared resource, you must call the recycle () method after obtaining the value.

Add attribute setting event

The custom attributes specified in xml can only be obtained when the view is initialized. Sometimes we may perform some operations during the runtime, in this case, we need to set the getter and setter methods for the custom attributes. The following code shows the set and get methods exposed by the custom control.

public boolean isShowText() {   return mShowText;}public void setShowText(boolean showText) {   mShowText = showText;   invalidate();   requestLayout();}

Focus on the setShowText method. After assigning values to mShowText, The invalidate () and requestLayout () methods are called. After the attributes of the custom control are changed, the display of the control may also change, in this case, you need to call the invalidate () method so that the system can call the onDraw () method of view to re-draw. Similarly, changes to control attributes may cause changes to the size and shape of controls. Therefore, we need to call requestLayout () to request measurement to obtain a new layout location.

2. process View layout. Measurement

A View always has its width and height during display. A measurement View aims to enable custom controls to be displayed with proper width and height based on different situations. When it comes to measurement, you must mention the onMeasure method. The onMeasure method is a view that determines its width and height.

<CODE class=" hljs java">@Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    }</CODE>

The onMeasure method has two important parameters: widthMeasureSpec and heightMeasureSpec. Here you only need to remember that they contain two information: mode and size.
We can use the following code to get the mode and size.

int specMode = MeasureSpec.getMode(measureSpec);int specSize = MeasureSpec.getSize(measureSpec);

What does the obtained mode and size represent?
Mode indicates that the parent control of the current control tells us how to layout the control.
Mode has three optional values: EXACTLY, AT_MOST, and UNSPECIFIED. Their meanings are:

EXACTLY: the parent control tells us that the child control has a fixed size and you can layout it according to the size. For example, we have specified a definite dp value and macth_parent.
AT_MOST: the current control cannot exceed a fixed maximum value, which is generally the case of wrap_content.
UNSPECIFIED.

The size is actually the size passed by the parent layout. The parent layout wants the size of the current layout.

The following is a fixed pseudocode Method for rewriting onMeasure:

If mode is EXACTLY {the parent layout already tells us the width and height of the current layout, therefore, we directly return the size} else {obtained from measureSpec to calculate the desired desiredSize if mode is AT_MOST and return the minimum value else in desireSize and specSize: return the calculated desireSize}

Although the above Code is basically fixed, there are a lot of steps to write. If you don't want to write it yourself, you can also use the tool method provided by android: resolveSizeAndState, this method requires two parameters: the size of the measurement and the size expected by the parent layout. It returns the correct size according to various situations. In this way, we don't need to implement the above template, just calculate the desired size and call resolveSizeAndState. Later, I will use this method to determine the size of a custom View.

After calculating the height and width, do not call the setMeasuredDimension () method in onMeasure. Otherwise, an exception occurs during running.

Calculate the value onSizeChange () required by some custom controls ()

The onSizeChange () method is called when the view is specified for the first time or the view size changes. Therefore, it is generally used to calculate values related to the view size.

3. Draw a View (Draw)

Once the custom control is created and the measurement code is written, you can implement onDraw () to draw the View. The onDraw method contains a Canvas parameter, onDraw () to put it simply, there are two points:
Canvas decides what to draw
Paint determines how to draw

For example, Canvas provides the draw line method, and painting determines the color of the line. Canvas provides a rectangle for painting, and painting can determine whether the rectangle is hollow or solid.

Before you start painting in the onDraw method, you should initialize the information of the Paint brush object. This is because the redrawing of views is frequent, which may call onDraw multiple times. Therefore, the initialization code should not be placed in the onDraw method.

Many methods provided by Canvas and Paint are not listed in this article. You can view the api on your own, which will be used in subsequent articles. Now you only need to understand the general steps of the definition, and then continue to learn more.

4. interaction with users

In some cases, your custom control not only displays beautiful content, but also supports user clicks, dragging, and other operations, at this time, the custom control requires the user interaction step.

The most common event in the android system is a touch event, which calls the onTouchEvent (android. view. MotionEvent) of the view. Rewrite this method to process our event logic.

  @Override   public boolean onTouchEvent(MotionEvent event) {    return super.onTouchEvent(event);   }

I believe everyone knows about the onTouchEvent method. If you don't know about it, remember that this is the place for processing Touch.

The current touch has more gestures, such as light and fast sliding. Therefore, you need to use the GestureDetector provided by android when supporting special user interaction. you only need to implement the corresponding interface in GestureDetector and process the corresponding callback method.

In addition to gestures, we also need to smooth the sliding animation if there is movement or something like that. The animation should start and end smoothly, rather than suddenly disappear. In this case, we need to use the property animation framework.

As there are many examples of knowledge involved in interaction with users, I will explain it in the Custom Control Article later.

5. Optimize your custom View

After the above steps are completed, a complete custom control has been developed. What you need to do next is to ensure that the custom control runs smoothly. The official saying is: to avoid the lag of your control, make sure that the animation remains 60 frames per second.

The following are the optimization suggestions on the official website:

1. Avoid unnecessary code
2. There should be no code in the onDraw () method that will lead to garbage collection.
3. Do not call the invalidate () method unless necessary.

Summary

At this point, the general steps and possible knowledge points of the custom control are all completed. See a picture.

The figure basically describes the general process of the custom control, and some knowledge points involved in the corresponding process on the right. You can see that custom controls include a lot of android knowledge. Therefore, it is necessary to learn android custom controls. When you can easily define a perfect custom control, I believe you are a good guy.

This article only gives a general introduction to the steps of the custom control. If you are not clear about the custom process, please remember the steps mentioned above, at least make a general impression. In subsequent articles, I will follow these steps to explain some custom controls and use the steps listed here to implement the custom controls we want step by step.

If there is something wrong with the article, please comment and correct it. After reading the article, please click here to comment! Thank you.

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.