Android Learning Scroller (v)--detailed scroller call process and view redraw

Source: Internet
Author: User

Mainactivity as follows:
Package Cc.ww;import Android.os.bundle;import Android.widget.imageview;import android.widget.ImageView.ScaleType; Import Android.widget.relativelayout;import Android.widget.relativelayout.layoutparams;import Android.app.activity;import Android.content.context;public class Mainactivity extends Activity {private Context    mcontext;private int [] imagesarray; Private Scrolllauncherviewgroup mscrolllauncherviewgroup; @Overrideprotected void OnCreate (Bundle savedinstancestate {super.oncreate (savedinstancestate); init ();} private void Init () {mcontext=this;imagesarray=new int []{R.DRAWABLE.A,R.DRAWABLE.B,R.DRAWABLE.C,R.DRAWABLE.D}; Mscrolllauncherviewgroup=new Scrolllauncherviewgroup (mcontext); ImageView imageview=null; Relativelayout.layoutparams layoutparams=null;for (int i = 0; i < imagesarray.length; i++) {imageview=new ImageView (MC Ontext); Imageview.setscaletype (SCALETYPE.FIT_XY); Imageview.setimageresource (Imagesarray[i]); layoutParams=new Layoutparams (Layoutparams.fill_parent, Layoutparams.fill_parent); Imageview.setlayoutparams (layoutparams); Mscrolllauncherviewgroup.addview (ImageView);} Setcontentview (Mscrolllauncherviewgroup);}}

Scrolllauncherviewgroup as follows:
Package Cc.ww;import Android.content.context;import Android.graphics.canvas;import android.util.AttributeSet; Import Android.view.motionevent;import Android.view.view;import Android.view.viewgroup;import Android.widget.scroller;import android.widget.toast;/** * Scroller principle: * In order to make the content of view or viewgroup move, we often use Scrollto () and Scrollby () method. * But both methods are executed quickly, and the movement feels rather stiff at a moment's completion. * To make the view or viewgroup content move more smoothly or have other moving gradients * can be implemented using Scroller. * In a specific implementation, when we inherit and rewrite view or viewgroup, we can generate a scroller by it to control the movement process and the combination of the Interpolator interpolator call Scrollto () and Scrollby () method. * * * * Scroller two main construction methods: * 1 public Scroller (context context) {} * 2 public Scroller (context context, interpolator Inter Polator) {} * with the first construction method, a default interpolator is used in the move Interpolator * or a second construction method to specify an interpolator for the move procedure interpolator * * Scroller call process and view redraw: * 1 call public void Startscroll (int startX, int starty, int dx, int dy) * This method does some preparatory work for scroll. * For example, set the starting coordinates of the movement, the distance and direction of the slide, and the duration. * This method is not really the beginning of sliding scroll, feel called preparescroll () more appropriate. * * 2 call Invalidate () or postinvalidate () to make the view (VieWgroup) Tree Redraw * Redraw the Draw () method that invokes view * Draw () a total of six steps: * Draw traversal performs several drawing steps which must be execut Ed * in the appropriate order: * 1. Draw the background * 2. If necessary, save the canvas ' layers to prepare for fading * 3. Draw View ' s content * 4. Draw Children * 5. If necessary, draw the fading edges and restore layers * 6.   Draw decorations (scrollbars for instance) * One of the most important is the third and fourth steps * The third step will call OnDraw () to draw the content * Fourth step will go to call Dispatchdraw () Draw Sub View *        Redraw in two cases: * 2.1 viewgroup Redraw * After completing the third Step OnDraw (), enter the fourth step ViewGroup rewrite the parent view of the Dispatchdraw () to draw the child view, so continue to call: * Dispatchdraw ()-->drawchild ()-->child.computescroll (); * 2.2 View Redraw * We note the "Call Invalidate ()" mentioned in 2. So how does it call the Computescroll () for view? View does not have a child view. So in the source of the view can be * see Dispatchdraw () is an empty method. So its call path and ViewGroup are not the same. * This begs the question: if a buttonsubclass extends Button is triggered when Mbuttonsubclass * executes the Mbuttonsubclass.scrollto () method Buttonsubcla SS classThe Computescroll () method in the override *??? * Here I am also more puzzled, only by the use of online information and source to see from the invalidate (). * This is generally true: when the view calls the Invalidate () method, it causes the entire view tree to redraw from top to bottom. For example, from the outermost layout to the layout of the layer, until each child view. * ViewGroup and view are logically passed onmeasure () and OnLayout () as well as the * OnDraw () method when redrawing the view tree. Of course, the system will determine whether the three methods must be executed, if not necessary, will not be called. * See here to understand: when the parent container of this child view is redrawn, the line mentioned above is also called: * OnDraw ()-->dispatchdraw ()-->drawchild ()-->child.computescro ll (); * The Computescroll () method that is overridden in the sub-view (for example, the Buttonsubclass class here) is called. * * 3 The redraw of the view tree will be called to the view in the Computescroll () method * 4 in the Computescroll () method * In the view source can see the public void Computescroll () {} is an empty method. * Specific implementations need to be written on their own. In this method we can call Scrollto () or Scrollby () * To implement the move. This method is the core of the implementation. * 4.1 Use Scroller's Mscroller.computescrolloffset () to determine if the move process is complete * Note: This method is a method in scroller rather than a!!!!!! in view * Public Boolean Computescrolloffset () {} *-this is the new location for want to know.   * If It returns true,the animation is not yet finished. * Loc'll Be altered to provide the new location. * Returns true to indicate that the move has not been completed yet. * 4.2 If the animation does not end, then call: ScrollTo (by) (); * Make it slide scrolling * * 5 call Invalidate () again. * Calling the Invalidate () method will then redraw the view tree. * Thus jumping to the 3rd step, so loop until Computescrolloffset returns FALSE * * * * Specific sliding process, see illustration * * * * * * * Popular Understanding: * from the above visible Scroller three core methods within the execution process * Mscroller.startscroll () * Mscroller.computescrolloffset () * View.computescroll () * 1 Some initial preparations are made for sliding in Mscroller.startscroll (). * For example: starting coordinates, distance and direction of sliding, and duration (with default values). * In addition to these, there are other things that are done within the method: * The more important thing is to set the animation start time. * * 2 Computescrolloffset () method calculates the current coordinate point based on the current elapsed time * and is stored in the Mcurrx and Mcurry values. * Because animation time is set in Mscroller.startscroll (), it is easy to get the current moment in the Computescrolloffset () method based on the elapsed time and save it in the variable Mcurrx and mcur The Ry. * In addition to this method you can also determine whether the animation has ended. * * So in this example: * @Override * public void Computescroll () {* Super.computescroll (); * IF (mscroller.compu  Tescrolloffset ()) {* ScrollTo (Mscroller.getcurrx (), 0); * invalidate (); *} * } * First execute Mscroller.computescrolloffset () determines whether the swipe ends * 2.1 returns FALSE, the swipe has ended. * 2.2 Returns TRUE, the swipe is not over yet. * The latest coordinate values MCURRX and Mcurry are also calculated within the method. * That means where to swipe at the current moment. * Since Computescrolloffset () so intimate, kindness with insistent ah! * So we're going to overwrite the view's Computescroll () method, * Call Scrollto (by) to swipe over there! It's a painstaking way to meet it. * * * NOTE: * 1 examples do not make boundary judgments and some optimizations, there are bugs in this area. * Emphasis is on learning the scroller process * 2 do not tangle Getcurrx () and GETSCROLLX () what is the difference between the two get the same value. * But be aware that they belong to different classes. * GETCURRX ()-------> Scroller.getcurrx () * GETSCROLLX ()-----> View.getscrollx () * * * Reference: * 0 http://android XREF.COM/2.3.6/XREF * 1 http://blog.csdn.net/wangjinyu501/article/details/32339379 * 2 http://blog.csdn.net/zjmdp/ article/details/7713209 * 3 http://blog.csdn.net/xiaanming/article/details/17483273 * Thank you very much * */public CLA    SS Scrolllauncherviewgroup extends ViewGroup {private int lastx;    private int currentx;    private int Distancex;    Private Context Mcontext; Private Scroller mscroller;public Scrolllauncherviewgroup (Context contEXT) {super (context); Mcontext=context;mscroller=new Scroller (context);} Public Scrolllauncherviewgroup (context context, AttributeSet Attrs) {Super (context, attrs);} Public Scrolllauncherviewgroup (context context, AttributeSet Attrs,int Defstyle) {Super (context, attrs, Defstyle);} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, HEIGHTMEASURESPEC);} /** * Note: * 1 getwidth () and getheight () get is the width and height of the screen * because the width and height of the control specified in the layout is fill_parent * 2 view.getscrollx (y) () to hit Mscrollx (y) * 3 tune With Scrollto (x, y), x and Y are assigned to MSCROLLX and mscrolly * Please note the coordinate direction. */@Overrideprotected void OnLayout (boolean arg0, int l, int t, int r, int b) {for (int i = 0; i < Getchildcount (); i++               {View Childview = Getchildat (i);   Childview.layout (I*getwidth (), 0,getwidth () + i*getwidth (), getheight ()); }} @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas);} @Overridepublic boolean ontouchevent (Motionevent event) {switch (EVENT.GETACtion ()) {case motionevent.action_down:lastx= (int) event.getx (); break;case motionevent.action_move:currentx= (int) Event.getx ();d Istancex=currentx-lastx;mscroller.startscroll (GETSCROLLX (), 0,-distancex, 0); break;case motionevent.action_up://your finger from the right side of the screen to the left, swipe to the next screen if (Distancex<0&&math.abs (Distancex) >50) { Mscroller.startscroll (GETSCROLLX (), 0, GetWidth ()-(GETSCROLLX ()%getwidth ()), 0);//swipe from the left of the screen to the right, swipe to the previous screen when your finger is lifted, or else if ( Distancex>0&&math.abs (Distancex) >50) {Mscroller.startscroll (GETSCROLLX (), 0,-(GetScrollX ()% GetWidth ()), 0);} Break;default:break;} Redraw view tree invalidate (); return true;} @Overridepublic void Computescroll () {super.computescroll (); if (Mscroller.computescrolloffset ()) {ScrollTo ( Mscroller.getcurrx (), 0); invalidate ();} Else{if (Mscroller.getcurrx () ==getwidth () * (Getchildcount ()-1) {Toast.maketext (Mcontext, "slide to last screen", Toast.length_ Short). Show ();}}}




























Main.xml as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent " >    <cc.ww.scrolllauncherviewgroup        android:id= "@+id/scrolllauncherviewgroup"        android:layout_ Width= "Fill_parent"        android:layout_height= "fill_parent"    /></relativelayout>


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.