This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Series of articles

This article takes you closer to Android custom Views


preface

From college to undergraduate course, the current undergraduate senior, is the fourth year of learning Android, intended to accumulate the 23 one’s deceased father grind, but has recently been bosses brainwashed after flushing for 22 one’s deceased father grind, so follow-up article risk is small, but in recently promised to fans to sort out a more detailed Android custom view tutorial, It happened that one of the student representatives who signed up and was selected by Huawei for the 2021 Hongmeng Open Course was on the way to ask for leave at school, so he spent a whole afternoon writing an article. (a little cold, if found mistakes please forgive me, thanks for correcting!!) .


The following is the content of the text, all the linked case notes are more detailed

Why customize a view

With the internal volume of major product managers, the built-in View of Android system has been unable to meet our needs. We need to customize the View we need for our own business to achieve a better user experience, so as to increase user stickiness.

Look at a super simple custom View (three constructors)

Textview is implemented in XML file. If there are two Textview lights in XML file, it will grab the focus and only run one. Create a Textview that automatically gets focused: isFocused();

Public Class MyTextView extends TextView {// Call public MyTextView(Context Context) {this(Context, null); } // This method is called when XML is recognized to create a Textview, Public MyTextView(Context Context, @nullable AttributeSet attrs) {this(Context, attrs, 0); } // Give the first constructor and the second constructor public MyTextView(Context Context, @nullable AttributeSet attrs, int defStyleAttr) {super(Context, attrs, defStyleAttr); } // Fix a problem that requires Textview to naturally get focus @override public BooleanisFocused() {
        return true; }}Copy the code

From the above code, I have written the function’s role into the remarks.

3. Understand the coordinate system of the phone

Specific case article: Android Canvas to draw a real running running lantern

4. Use Canvas to draw a line graph (override onDraw () method)

DrawLine (); drawText(); drawLine();

Specific case article: Android uses Canvas to draw a line chart and encapsulates it simply

5, how to customize the property, and obtain the value of the property in the view (small mention, there will be cases in 6)

Take color, for example.

Attrs file <attr name="leftcolor" format="reference|color"/>
        <attr name="rightcolor" format="reference|color"/> // Java file --TaiJiView for custom view name // get custom attributes. TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TaiJiView); Int leftColor = ta.getColor(r.tyleable.taijiView_leftColor, color.black); int rightcolor=ta.getColor(R.styleable.TaiJiView_rightcolor, Color.WHITE); / / recovered ta. Recycle (); // App in layout :leftcolor="@color/colorPrimary"
        app:rightcolor="#ff0000"
Copy the code

Six, draw patterns and add simple animation Settings (the case is very detailed)

Canvas. DrawCircle, rotation animation

Specific case article: Android custom view taiji diagram

Seven, the implementation of custom view classification and custom combination control case

  • Custom composite controls: Combine multiple controls into a new control. (This case)
  • Inheriting system controls: the title 2 case
  • Inheriting views: as in heading 6
  • Inherit ViewGroup: Inherit from system controls such as LinearLayout and extend the basic functions of system controls.

Specific case article: Android custom View imitation login interface text input box (Huawei cloud APP)

Simple measurements and custom interface instances to control animated update evaluation expressions (onMeasure, TypeEvaluator)

The project source code is posted at the end of the linked article

Specific case article: Android custom view of go animation

Nine, by changing the value of variables to achieve animation effect

Android custom view using drawArc method to achieve dynamic effects

Android custom View go animation (simplify complexity)

Android custom view using PathEffect dynamic effect

Android custom View lines waiting for animation (inspiration: Golden Shovel Battle)

Ti: Move the drawing point to the center. The code looks a little bit cleaner

X. When the interface updates frequently (SurfaceView)

Talk about Android SurfaceView for custom Views

GLSurfaceView (inherited from SurfaceView, 3D effect)

Android custom view 3D cube

If you want to go further, please also learn about openGL.

About SVG

Android using SVG animation effect Detailed example of Android SVG animation

A simple Github example

Android Line Wait animation JMWorkProgress

14, have not had time to write (key words)

Bezier curve, event distribution mechanism. Enumeration (can be used in frames to determine animation state)

Fifteen, two interview related eight tips (according to my interview)

1.View drawing process

Views are drawn from the performTraversals() method of ViewRootImpl, and each View is drawn layer by layer from the top View(ViewGroup).

View drawing process is divided into three stages: measure, layout and draw.

Measure: WidthMeasureSpac and heightMeasureSpac are used to measure the width and height of a custom view. WidthMeasureSpac and heightMeasureSpac are used to measure the width and height of a custom view. So the width and height of the child layout needs to be limited by the parent layout.

Layout: Layout () passes four position parameters to setOpticalFrame() or setFrame() according to the layout size and layout parameters obtained by measure subviews. SetFrame () is called inside setOpticalFrame(), so setFrame() is used to determine the position of the View in the ViewGroup. After the location is determined, onLayout(L, T,r, B) will be called to place the sub-view.

Draw: Draws a View object onto the screen.

  • Canvas: no matter the text, graphics or pictures are drawn on Canvas
  • Paint: you can set the color, thickness, size, shadow, etc. It is usually used with the canvas
  • Path: A Path used to form irregular shapes.
  • Matrix: Matrix, which can realize the geometric transformation of the canvas.

2. Event distribution mechanism of View

The type of touch event

Touch events correspond to the MotionEvent class, and there are three main types of events:

  • ACTION_DOWN
  • ACTION_MOVE(Moves beyond a certain threshold will be considered an ACTION_MOVE action)
  • ACTION_UP

View event distribution is essentially the process of MotionEvent distribution. When a MotionEvent occurs, the system passes the click event to a specific View.

Event Distribution Process

The event distribution process is accomplished in three ways:

DispatchTouchEvent: method returns true to indicate that the event is consumed by the current view; A return of super.dispatchTouchEvent means that the event continues to be distributed, and a return of false means that onTouchEvent processing is handed to the parent class.

OnInterceptTouchEvent: The method returns true to intercept the event and send it to its own onTouchEvent method for consumption; Returning false means no interception and needs to continue to be passed to the subview. If return super. OnInterceptTouchEvent (ev), event interceptor in two situations:

  • 1. If the View has a child View and the child View is clicked, it will not be intercepted and continue to be distributed to the child View for processing, equivalent to return false.

  • 2. If the View does not have children or has children but does not click on the neutron View(in this case the ViewGroup is equivalent to a normal View), the onTouchEvent of the View will respond, which is equivalent to return true.

Viewgroups such as LinearLayout, RelativeLayout, and FrameLayout are not blocked by default, whereas viewgroups such as ScrollView and ListView are blocked by default.

OnTouchEvent: method returns true to indicate that the current view can process the corresponding event; A return value of false means that the event is not handled by the current view and is passed to the parent view’s onTouchEvent method for processing. If return super.onTouchEvent(EV), event handling is divided into two cases:

  • 1. If the View is clickable or longClickable, return true, indicating that the event was consumed.

  • 2. If the View is not clickable or longClickable, false will be returned, indicating that the event is not consumed and will be passed up, just as false is returned.

Note: In Android, there are three classes with event-passing capabilities:

  • Activity: Has both distribution and consumption methods.

  • ViewGroup: has distribute, intercept, and consume methods.

  • View: Has distribution and consumption methods.