Android Custom ViewGroup

Source: Internet
Author: User

In the previous sections, we focused on customizing the view's kick, and this section discusses custom ViewGroup, why customizing the ViewGroup is really about managing the view better.

Custom ViewGroup is nothing more than a few steps:

Ⅰ, override the Onmeasure () method to test the size of the child control.

Ⅱ, overriding the OnLayout () method, calculates the layout of the child controls.

Ⅲ, in the OnDraw () method, draws a child control, which is optional.

Ⅳ, listens for Ontouch events, responds to screen touch events.

The corresponding mind map is as follows:

Great length said so much, we use a small case to understand this custom viewgroup to see how to implement ViewGroup.

Simple viscous ScrollView

Simple overview

This is a very similar effect of a native scrollview effect, and he can swipe up and down like ScrollView, but we add a sticky effect. What is the viscous effect? That is, when a child view is sliding upwards above a certain distance, it will automatically swipe up to show the next child view. Similarly, if a sub-view slide distance is less than a certain distance, it rolls back to its original position.

  Implementation ideas

To find the angle of shooting, control to find ideas. Let's analyze the basic idea to implement this custom ViewGroup:

Ⅰ, in the Onmeasure () method, measures the size of each child control.

Ⅱ, in the OnLayout () method, calculates the position of each control to be displayed.

Ⅲ, followed by, is in the Ontouchevent () method, listening to the gesture touch event, to determine whether it is sliding or falling, to determine if its sliding distance is greater than the value we set, if greater than this value, it will be moved to the next sub-view, otherwise, roll back to the original position.

With this idea, all we need to do is step-by-step implementation of code writing

  Specific implementation

The first step, the initialization of some variables, the code is as follows:

    Private void init (Context context) {        = (windowmanager) context                . Getsystemservice (context.window_service);         New  displaymetrics ();        Manager.getdefaultdisplay (). Getmetrics (displaymetrics);         = displaymetrics.heightpixels;         New Scroller (context);    }

Gets the screen height as the height of each control, initializing the Scroller control.

The second step, the implementation of the control measurement, the code is as follows:

@Override     protected void onmeasure (intint  heightmeasurespec) {        super. Onmeasure ( Widthmeasurespec, Heightmeasurespec);         int count = getchildcount ();          for (int i = 0; i < count; i++) {            = Getchildat (i);            Measurechild (Child, Widthmeasurespec, Heightmeasurespec);        }    }

We see that the size of each child control is consistent with the size of the parent control in order to create a scrolling effect.

In the third step, the child controls are arranged from top to bottom, as shown in the following code:

@Overrideprotected voidOnLayout (BooleanChangedintLintTintRintb) {intCount =Getchildcount (); Marginlayoutparams Layoutparams=(Marginlayoutparams) getlayoutparams (); Layoutparams.height= Mscreenheight *count;  for(inti = 0; I < count; i++) {View child=Getchildat (i); if(child.getvisibility () = =view.visible) {child.layout (L, I* Mscreenheight, R, (i + 1) *mscreenheight); }        }    }

We can clearly see that if the child controls are arranged from top to bottom, the sub-control takes one frequency, so that the necessary conditions for scrolling up and down can be formed.

The fourth step, the listening gesture event, the source code is as follows:

@Override Public Booleanontouchevent (Motionevent event) {inty = (int) event.gety (); Switch(Event.getaction ()) { CaseMotionEvent.ACTION_DOWN:mLastY=y; Mstart=getscrolly ();  Break;  CaseMotionevent.action_move:if(!mscroller.isfinished ())            {mscroller.abortanimation (); }            intDy = y-Mlasty; if(getscrolly () < 0) {dy= 0; } Else if(getscrolly () > GetHeight ()-mscreenheight) {dy= 0; } Scrollby (0, DY); Mlasty=y;  Break;  CaseMotionEvent.ACTION_UP:mEnd=getscrolly (); intDelta = mEnd-Mstart; if(Delta > 0) {                if(Delta < MSCREENHEIGHT/3) {Mscroller.startscroll (0, getscrolly (), 0,-Delta); } Else{Mscroller.startscroll (0, getscrolly (), 0, Mscreenheight-Delta); }            } Else {                if(Math.Abs (delta) < MSCREENHEIGHT/3) {Mscroller.startscroll (0, getscrolly (), 0,-Delta); } Else{Mscroller.startscroll (0, getscrolly (), 0,-Mscreenheight-Delta); }            }             Break; default:             Break; }        return true; }

  Summary afterwards

In fact, three events were made in this event monitoring.

①, according to gesture Press, lift the distance to judge, judging whether the gesture is on the slide or decline.

②, if the gesture slide distance, less than the corresponding threshold (here is the screen height of one-third), then roll back to the original position, or automatically slide into the next child view.

③, moves the event at the finger, allowing the control to move freely as the gesture slides. However, we should judge the corresponding critical value, whether it is less than 0 or greater than the screen height, do not slide.

  Final effect 

The effect of this control's final run is:

That is, I have a summary of the custom ViewGroup control. I Caishuxueqian, I implore you to advise.

Android Custom ViewGroup

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.