Android authoritative Programming Guide-notes (29th. Customizing views and Touch events)

Source: Internet
Author: User

1. Customizing the View

Android comes with many excellent standard views and components, but sometimes we still need to create custom views for the pursuit of unique application visuals.

Custom views fall into two main categories:

    • Simple view: The inside of a simple view can also be complex and classified as a simple category because simple views do not include child views, and simple views almost always perform custom drawing.
    • Aggregated views: Aggregated views are made up of other view objects, which typically manage child views, but are not responsible for custom drawing, and the graphical drawing tasks are delegated to each child view.

  

The three major steps required to create a custom view:

    •   Select the superclass. for a simple custom view, viewis a blank canvas , so it is most common as a superclass, and for aggregated custom views, we should choose the appropriate superclass layout, such as Framelayout.
    •   Inherits the selected superclass and overrides at least one superclass construction method.
    •   Override other critical methods to customize the view behavior.

1.1 Creating a simple view class

 public   Class  Boxdrawingview extends   View { //     used when creating the view in code  public   Boxdrawingview (context context) { this  (CO    ntext, null   //  used when inflating the view from XML public   Boxdrawingview (context context, AttributeSet attrs) { super   (context, attrs    ); }}

A view that is instantiated from a layout file receives an instance of AttributeSet that contains the XML attributes specified in the XML layout file. even if you do not intend to use construction methods, you should also add them as a custom practice.

With the custom view class, you can reference it in the layout file.

< Com.bignerdranch.android.draganddraw.BoxDrawingView     xmlns:android = "Http://schemas.android.com/apk/res/android"     android:layout_width= "Match_parent"    android:layout_height= "Match_ Parent "/>

You must use the full pathname of a custom view when referencing, so that the layout inflater can find it, the layout file Inflater parse the layout XML file, and the view instance is created by definition, if the element name is not the full path name, the layout inflater

Will instead look for targets in the Android.view and android.widget packages, and if the target view is placed in another package, the layout inflater will not be able to find the target and eventually cause the app to crash.

Therefore, for custom view classes other than the Android.view and Android.widger packages, you must specify their full path names.

1.2 Handling Touch Events

One way to listen for touch events is to set up a touch event listener using the following view method:

Public void Setontouchlistener (view.ontouchlistener L)

However, our custom view is a subclass of view, so we can take a short cut to cover the following view methods directly:

 Public boolean ontouchevent (Motionevent event)

The method receives an instance of the Motionevent class, and the Motionevent class can be used to describe touch events that include position and action. Actions are used to describe the stage in which the event is located.

Action constants Action Description
Action_down Finger touch to screen
Action_move Finger moves on the screen
Action_up Finger off the screen
Action_cancel The parent view intercepts touch events

In the Ontouchevent () implementation method, you can use the following motionevent methods to view the action values:

 Public Final int getaction ()

Our goal is to record the drop position when one finger is down, and change it when moving, and fix the rectangle when it is released. And the previously drawn rectangular box data needs to be recorded.

Create an entity class that represents the definition data for a rectangle box. Used to hold the original coordinate point (the initial position of the finger) and the current coordinate point (the current position of the finger):

 Public class Box {    private  PointF morigin;     Private PointF mcurrent;      Public Box (PointF origin) {        = origin;         = origin;    }
Get, set slightly}

Then rewrite the Ontouchevent () method and take the appropriate action:

PrivateBox Mcurrentbox;PrivateList<box> Mboxen =NewArraylist<>(); @Override Public Booleanontouchevent (Motionevent event) {//each time a touch event is recorded, the coordinates are nowPointF current =NewPointF (Event.getx (), event.gety ()); String Action= ""; Switch(event.getactionmasked ()) { CaseMotionEvent.ACTION_DOWN:action= "Action_down"; //Add a box to the list each time you pressMcurrentbox =NewBox (current);            Mboxen.add (Mcurrentbox);  Break;  CaseMotionEvent.ACTION_MOVE:action= "Action_move"; if(Mcurrentbox! =NULL) {            //Redraw when you're moving.mcurrentbox.setcurrent (current);            Invalidate (); }             Break;  Casemotionevent.action_up://when lifted, no longer points to the latest BoxAction = "ACTION_UP"; Mcurrentbox=NULL;  Break;  CaseMotionEvent.ACTION_CANCEL:action= "Action_cancel"; Mcurrentbox=NULL;  Break; } log.i (TAG, Action+ "at x=" + current.x + ", y=" +current.y); Zreturn true;}

When you cancel a touch event or the user's finger leaves the screen, the mcurrentbox should be emptied to end the screen drawing, and the box to complete will be stored securely in the array.

The invalidate () method forces Boxdrawingview to redraw itself so that the rectangle can be seen in real time while dragging.

2 OnDraw () graphical drawing within the method

When the app starts, all views are in an invalid state (the view has not been drawn to the screen), and to solve this problem, Android invokes the draw () method of the top-level view view, which causes a top-down chain call to be reflected.

First, the view finishes self-drawing, then the child view's self-drawing, then the child view's child view's self-drawing, so called down to the end of the inheritance structure. When all views in the inheritance structure are self-drawn, the top-level

View views are also in effect.

To join this drawing, you can override the following View methods:
   protected void OnDraw (canvas canvas);

In response to the Action_move action in the Ontouchevent () method, we call the Invalidate () method again to invalidate the Boxdrawingview, forcing him to re-draw himself and invoke the OnDraw () method again.

  

Canvas and paint are two of the most well-drawn classes of Android systems.

    • The canvas class has all the drawing operations we need, and its methods determine where and what to draw, such as lines, circles, words, rectangles, and so on.
    • The Paint class determines how to draw, with methods that specify the characteristics of the drawing, such as whether to fill the shape, what font to use, what color the line is, etc.

  

  PublicBoxdrawingview (context context, AttributeSet Attrs) {//The AttributeSet instance contains the XML attributes specified in the XML layout file.         Super(Context,attrs); Mboxpaint=NewPaint (); Mboxpaint.setcolor (0x22ff0000); Mbackgroundpaint=NewPaint (); Mbackgroundpaint.setcolor (0xfff8efe0); } @Overrideprotected voidOnDraw (canvas canvas) {//draw the background firstCanvas.drawpaint (Mbackgroundpaint); //draw each drawn rectangle         for(Box box:mboxen) {floatleft =math.min (Box.getorigin (). x, Box.getcurrent (). x); floatright =Math.max (Box.getorigin (). x, Box.getcurrent (). x); floattop =math.min (Box.getorigin (). Y, Box.getcurrent (). y); floatBottom =Math.max (Box.getorigin (). Y,box.getcurrent (). y);        Canvas.drawrect (left, top, right, bottom, mboxpaint); }    }

The first part of the above code is straightforward: Use the white background paint, fill the canvas to foil the rectangle box. Then, for each rectangle in the rectangular box array, according to its two point coordinate, determine the position of the rectangle box up or down. When drawn, the value of the left and top values as the minimum, right and bottom values as the maximum value. After the position coordinate value calculation is completed, call the Canvas.drawrect (...) method to draw a red rectangle on the screen.

  

Android authoritative Programming Guide-notes (29th. Customizing views and Touch events)

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.