Teach you to take care of Android custom view

Source: Internet
Author: User

Android app development process, many times will encounter the system framework provided by the control can not meet the design needs of our products, then we can choose to first Google under the more mature open source projects can let us use, of course, now GitHub above the project is very rich, To meet our most demanding development needs, but when we use these cool third-party controls, we also have to think about whether we can play our own imagination, implement the controls we want, and control the details of the implementation as much as possible!

View

All Android controls are either view or subclass of view, which actually represents a rectangular area on the screen, represented by a rect, and Left,top represents the starting point of the view relative to its parent view, width, The height represents the view's own width, and with these 4 fields you can determine the position of the view on the screen, and then you can start to draw the view after you have determined the position.

View Drawing Process

The drawing of a view can be divided into the following three processes:

  • Measure view will do a measurement first to figure out how much area you need to occupy. The measure process of view exposes us to an interface onmeasure, which is defined by the method,

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {}

    The view class already provides a basic onmeasure implementation,

    ProtectedvoidOnmeasure (int Widthmeasurespec,int heightmeasurespec) {setmeasureddimension (Getdefaultsize (Getsuggestedminimumwidth (), WidthMeasureSpec), Getdefaultsize (Getsuggestedminimumheight (), Heightmeasurespec));}public static int getdefaultsize ( int size, int measurespec) {int result = size; int Specmode = Measurespec.getmode (Measurespec); int specsize = Measurespec.getsize (Measurespec); switch (specmode) {case MeasureSpec.UNSPECIFIED:result = size ; break; case measurespec.at_most: case MeasureSpec.EXACTLY:result = Specsize; break;} return result;}            

    Which invoke the Setmeasureddimension () method, set the measure process the width of the view, Getsuggestedminimumwidth () return to the view of the minimum width,height also has a corresponding method. In a few words, the Measurespec class is an internal static class of the view class, which defines three constants unspecified, At_most, exactly, in fact, we can understand it this way, they correspond to Layoutparams in Match_parent , Wrap_content, XXXDP. We can rewrite the onmeasure to redefine the view's wide height.

  • The layout layout process is very simple for the view class, and the same view exposes us to the OnLayout method

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {}

    Because we're talking about view, no sub-view needs to be arranged, so this step actually doesn't need to do any extra work. In the ViewGroup class, in the OnLayout method, we need to set the size and width of all sub-view sets, which we will say in detail next.

  • The draw draw process is to draw the view style that we need on the canvas. The same view exposes us to the OnDraw method.

    protected void onDraw(Canvas canvas) {}

    The default view class's OnDraw does not have a single line of code, but provides us with a blank canvas, for example, like a picture scroll, we are painters, can draw what kind of effect, completely depends on us.

    There are three more important methods in view
  • Requestlayout View re-invokes the layout process.

  • Invalidate view re-calls the draw process

  • Forcelayout identifies the view in the next redraw and needs to recall the layout process.

Custom properties

The entire view of the drawing process we have finished, there is a very important knowledge, custom control properties, we all know that the view has some basic properties, such as Layout_width,layout_height,background, We often need to define our own properties, so we can do that.

  • 1. In the Values folder, open Attrs.xml, in fact, this file name can be arbitrary, write here more standard point, that is all the properties of the view is placed inside.
  • 2. Because the following example will use 2 length, a color value of the property, so we first create a 3 properties.

    <Declare-styleableName="Rainbowbar" ><attrName="Rainbowbar_hspace" format="Dimension" ></attr> <attr name=" Rainbowbar_vspace " format=" Dimension "></attr> <attr name=" Rainbowbar_color " format=" Color "></attr></declare-styleable>  

So how to use it, we'll look at an example.

Implement a simple Google Rainbow progress bar.

For the sake of simplicity, here I only use a color, a variety of colors left to everyone, we directly on the code.

The Blue progress bar
PublicClass Rainbowbar extends View {progress bar Colorint barcolor = Color.parsecolor ("#1E88E5");Every bar segment widthint hspace = UTILS.DPTOPX (Getresources ());Every bar segment heightint vspace = UTILS.DPTOPX (4, Getresources ());Space among barsint space = UTILS.DPTOPX (Getresources ());float StartX =0;float Delta =10f; Paint Mpaint;PublicRainbowbar(Context context) {Super (context);}PublicRainbowbar(context context, AttributeSet attrs) {This (context, attrs,0); }public RainbowBar (context context, AttributeSet attrs, int defstyleattr) {Super (context, attrs , defstyleattr); //read custom attrs TypedArray t = context.obtainstyledattributes (Attrs, R.styleable.rainbowbar, 0, 0); hspace = T.getDimensionPixelSize (R.styleable.rainbowbar_rainbowbar_hspace, hspace); vspace = T.getdimensionpixeloffset (R.styleable.rainbowbar_rainbowbar_vspace, vspace); Barcolor = T.getcolor (R.styleable.rainbowbar_rainbowbar_color, Barcolor); T.recycle (); //we should always recycle after used mpaint = new Paint (); mpaint . Setantialias (true); Mpaint.setcolor (Barcolor); Mpaint.setstrokewidth (vSpace);} .......}

View has three constructor methods that we need to rewrite, here we introduce the next three methods will be called scene,

    • The first method, typically called when we use this, is the view view = new view (context);
    • The second method, when we use View in an XML layout file, is called when the inflate layout is <view layout_width= "match_parent" layout_height= "Match_parent"/>.
    • The third method, similar to the second, but adds the style property setting, when the Inflater layout calls the third construction method. <view style= "@styles/mycustomstyle" layout_width= "match_parent" layout_height= "Match_parent"/>.

It may seem a little confusing to me that I have initialized the read from the definition attribute hspace,vspace, and Barcolor's code is written in the third constructor, but I rainbowbar not add the style attribute in the linear layout (), which, as we explained above, Inflate layout should invoke the second construction method, but we call the third constructor in the second constructor method, this (context, attrs, 0); So in the third construction method read the custom attribute, no problem, this is a little detail, avoid code redundancy-,-

Draw

Because we don't have to pay attention to the measrue and layout process, we can rewrite the OnDraw method directly.

 Draw be invoke numbers.int index =0;@OverrideProtectedvoidOnDraw (Canvas canvas) {super.ondraw (canvas);Get screen widthfloat SW =This.getmeasuredwidth ();if (StartX >= SW + (hspace + space)-(sw% (hspace + space))) {StartX =0; }else {StartX + = Delta;}float start = StartX;Draw latter Parsewhile (Start < SW) {Canvas.drawline (Start,5, start + hspace,5, Mpaint); Start + = (hspace + space); } start = Startx-space-hspace;Draw Front Parsewhile (start >=-hspace) {canvas.drawline (Start,5, start + hspace,5, Mpaint); Start-= (hspace + space); }if (Index >=700000) {index =0; } invalidate ();}Layout file <?xml version="1.0" encoding="Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" Xmlns:app= " Http://schemas.android.com/apk/res-auto "Android:layout_width=" Match_parent "Android: Layout_height= "match_parent" Android:gravity= "center" Android:layout_margintop= "40DP" Android:orientation= " Vertical "><com.sw.demo.widget.rainbowbar android:layout_width=" match_parent " Android:layout_height= "wrap_content" App:rainbowbar_color= " @android: Color/holo_blue_bright "App:rainbowbar_hspace=" 80DP "app:rainbowbar_vspace=< Span class= "hljs-string" > "10DP" ></COM.SW.DEMO.WIDGET.RAINBOWBAR></LINEARLAYOUT>   

is actually called the canvas's DrawLine method, and then each time the starting point of draw forward, at the end of the method, we call the Invalidate method, which we have explained, this method will let the view recall OnDraw method, So just reach the effect that our progress bar has been drawing forward. Here is the final display effect, made into GIF as if the color difference, but the real effect is blue. We only wrote a short dozens of lines of code, custom view is not as difficult as we thought, the next we will continue to viewgroup drawing process learning.

Rainbow_bar_demo.gif Wen/alious (Jane book author) The original link: http://www.jianshu.com/p/84cee705b0d3 copyright belongs to the author, reprint please contact the author to obtain authorization, and Mark "Jane book author".

Teach you to take care of Android custom view

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.