Several ways to implement view sliding in Android

Source: Internet
Author: User

Note: This article refers to the complete demo:scrolldemo1 of all three sliding modes. What we need to know about view (1) What is view?

The view class in Android is the base class for all UI controls (base class), which means that all of the various UI controls we normally go to, such as Button, Imagview, and so on, inherit from the view class. The direct parent class of the layout manager, such as LinearLayout, Framelayout, is ViewGroup, and ViewGroup also has a view class derivation. In general, view is an abstraction of the UI control, which represents a rectangular area on the screen. By inheriting view and overriding the appropriate methods, we are able to implement UI controls with various appearances and behaviors. Buttons and other controls we are able to use them directly because Google has helped us with the work of inheriting view and rewriting methods.

(2) Location of view

The location of the view on the screen is determined by the following four parameters:

    • The vertical axis of the upper-left corner of the Top:view corresponds to the member variable mtop in the View class, which can be obtained by the GetTop method;
    • The horizontal axis of the upper-left corner of the Left:view corresponds to the member variable Mleft in the View class, which can be obtained by the GetLeft method;
    • The ordinate of the lower right corner of the bottom:view corresponds to the member variable Mbottom in the View class, which can be obtained by the Getbottom method;
    • The horizontal axis of the lower-right corner of the right:view corresponds to the member variable mright in the View class, which can be obtained by the GetRight method.

Note that the coordinates above are relative to the parent view, that is, the coordinates are relative coordinates, because the layout of the child view is done by the parent view. As shown in the following:

With these four parameters, it is easy to calculate the width of a view: width = Right-left;height = Bottom-top. There are two parameters to note about view: Translationx represents the horizontal distance of the view translation, Translationy represents the vertical distance of the view translation, and x, y are the horizontal ordinate of the upper-left corner of the view, respectively. If the view has been panned, it changes its x, Y (representing the position of the top left corner of the current view), and its four positional parameters represent the original location information of the view, which is always the same. View always meets the following relationships during panning:

x = left + Translationx; y = top + translationy.

2. Several ways to implement view swipe

In the process of using view, we often need to realize the sliding effect of view. For example, a ListView, a custom view that moves with a finger, and so on, the slide effect of the former is provided by the SDK, and the sliding effect of our custom view needs to be implemented by ourselves. Let's go through the following several ways to implement view sliding in detail below.

(1) using Scrollto/scrollby to realize the sliding of view

The simplest and most straightforward way to achieve sliding is to use the Scrollto/scrollby method that comes with the view class. The Scrollby method is to slide the specified displacement amount, while the Scrollto method is to slide to the specified position. The source code for these two methods is as follows:

1/**2 * Set the scrolled position of your view. This would cause a call to 3 4 * {@link#onScrollChanged (int, int, int, int)} and the view would be 5 6 * invalidated. 7 8 *@paramx The x position to scroll to 9 *@paramy the y position to scroll*/13 Public voidScrollTo (intXinty) {14if(MSCROLLX! = x | | mscrolly! =y) {15intOLDX =Mscrollx; 16intOldY =mscrolly; MSCROLLX =x; mscrolly =y; 19onscrollchanged (MSCROLLX, mscrolly, OLDX, OldY); 20if(!Awakenscrollbars ()) {  21stinvalidate (); 22           }  23       }  24 }  25 26/*** Move The scrolled position of your view. This would cause a call to * {@link#onScrollChanged (int, int, int, int)} and the view would be invalidated *. *@paramx The amount of pixels to scroll by horizontally *@paramy the amount of pixels to scroll by vertically*/33 Public voidScrollby (intXinty) {ScrollTo (mscrollx + x, mscrolly +y); 35}

Through the 33~35 line of the above code we can see that the Scrollby method is also called the Scrollto method to implement. In the above source we notice the MSCROLLX and mscrolly member variables, which are the left edge of the view minus the contents of the view, which is the top edge of the view minus the contents of the view. As follows:

, the black border represents the rectangular area of view on the screen, and the blue border represents the contents of the view. In, we call Scrollto/scrollby to scroll the view to the right for a certain distance. In fact, invoking the Scrollby/scrollto method only allows scrolling of the contents of the view, while the four positional parameters of the view remain unchanged. Think about our usual use of the ListView, scrolling is the content of the ListView, and the ListView itself on the screen position is unchanged. , the left side of the black (the left edge of the view) is subtracted from the left side of the blue (that is, the left edge of the view's content) to get mscrollx. We can also know that when scrolling to the right mscrollx negative, MSCROLLX is positive when scrolling to the left. Similarly we can know that when scrolling down, mscrolly is negative, and when scrolling up, mscrolly is positive.

After the above analysis, we understand that using the Scrollto/scrollby method to realize the sliding of the view is very simple and straightforward, so what is the cost behind the simple? The price is that the slide is not "elastic", and the sliding means that the view slide should be a process of accelerating and slowing down to the stop, so that it looks smooth and not very abrupt. The slide that the Scrollto/scrollby method implements will look abrupt, so the user experience is not good. Before we solve this problem, let's look at other ways to implement the view swipe.

(2) Using animation to realize the sliding of the view

The use of animation to realize the sliding of the view is mainly achieved by changing the Translationx and Translationy parameters of the view, the advantage of using animation is that the sliding effect is smooth. As we mentioned above, the x and Y parameters of the view determine the current position of the view, and by changing the Translationx and translationy, we can change the view's current position. We can use property animations or motion tweens to achieve the panning of a view.

First, let's take a look at how to use motion tweens to translate the view. The Tweened animation resource is defined as follows (Anim.xml):

<?XML version= "1.0" encoding= "Utf-8"?><Setxmlns:android= "Http://schemas.android.com/apk/res/android"Android:fillafter= "true">    <Translateandroid:duration= "+"Android:fromxdelta= "0"Android:fromydelta= "0"Android:interpolator= "@android: Anim/linear_interpolator"Android:toxdelta= "+"Android:toydelta= "+"/></Set>

You can then call the Startanimation method in the Oncreat method. Using motion tweens to realize the sliding of a view is a flaw, that is, the "image" of the Moving knowledge view, which means that the view is not actually moving, but we seem to move it. Take the button for example, if we move a button through the motion tween, we will find that clicking on the screen in the original position of the button will start hitting the event, and clicking on the button on the move will not trigger the Click event.

Next, let's look at how to use property animations to translate the view. Using property animations to realize the panning of a view is simpler and requires only one of the following statements:

Objectanimator.offloat (TargetView, "Translationx", 0, +). Setduration (+). Start ();

The above code is implemented using the property animation to the TargetView within 100ms to the right to translate 100px. The limitation of using property animations is that real property animations can only be used on Android 3.0+ (some third-party libraries implement a lower-compatible property animation that is not a true property animation), and the advantage is that it can actually move the view instead of just moving the view image.

After the above description, the use of property animation to achieve the view of the sliding look is a good choice, and some view of the complex sliding effect only through the animation can be more convenient implementation.

(3) by changing the layout parameters to achieve the sliding view

The idea of sliding the view by changing the layout parameters is simple: for example, to move a view to the right, simply increase its marginleft parameter and move it in other directions, just change the corresponding margin parameter. A more roundabout approach is to pre-place a view next to the view you want to move (the initial width height is set to 0). Then, for example, to move the view to the right, simply increase the width of the pre-placed view so that the view is "squeezed" to the right. The code examples are as follows:

Marginlayoutparams params =+ = +; mbutton.requestlayout ();

The above code is implemented to slide the Mbutton to the right 100px. The sliding effect achieved by changing the layout parameters is also not smooth.

(4) using scroller to achieve elastic sliding

Above we mentioned that using the Scrollto/scrollby method to realize the sliding effect of view is not smooth, the good news is that we can use the Scroller method to assist the implementation of the view of the elastic sliding. The idiomatic code for using scroller to achieve elastic sliding is as follows:

1Scroller Scroller =NewScroller (mcontext);2 3 Private voidSmoothscrollto (intDstX,intdsty) {4     intSCROLLX =getscrollx ();5     intDelta = DstX-Scrollx;6Scroller.startscroll (SCROLLX, 0, Delta, 0, 1000);7 invalidate ();8 }9 Ten @Override One  Public voidComputescroll () { A     if(Scroller.computescrolloffset ()) { - ScrollTo (Scroller.getcurrx (), Scroller.getcury ()); - postinvalidate (); the     } -}

Let's take a look at the above code. In line 4th, we get the MSCROLLX parameter of the view and coexist to the SCROLLX variable. Then, on line 5th, calculate the amount of displacement to slide. Line 6th calls the Startscroll method, let's take a look at the source code of the Startscroll method:

1  Public voidStartscroll (intStartX,intStarty,intDxintDyintduration) {  2Mmode =Scroll_mode; 3mfinished =false; 4Mduration =duration; 5Mstarttime =Animationutils.currentanimationtimemillis (); 6Mstartx =StartX; 7Mstarty =Starty; 8Mfinalx = StartX +DX; 9Mfinaly = Starty +dy; TenMdeltax =DX;  OneMdeltay =dy;  AMdurationreciprocal = 1.0f/(float) mduration;  -      -Mviscousfluidscale = 8.0f;  the     -Mviscousfluidnormalize = 1.0f;  -Mviscousfluidnormalize = 1.0f/viscousfluid (1.0f);  -}

From the above source code, we can see that the Startscroll method does not carry out the actual scrolling operation, but the StartX, Starty, DeltaX, DeltaY and other parameters are preserved. So how in the world do you realize the sliding of the view? Let's go back to scroller idiomatic code. We see that line 7th calls the Invalidate method, which requests that the view be redrawn, which causes the view's draw method to be called, and the Computescroll method is called inside the draw method. Let's take a look at line 13th, call the Scrollto method, and pass in the Mscroller.getcurrx () and Mscroller.getcurry () methods as arguments. So what are the two parameters obtained? These two parameters are set in the Computescrolloffset method called in line 12th, so let's take a look at the related code that sets the two parameters in this method:

1  Public BooleanComputescrolloffset () {2     ...3     inttimepassed = (int) (Animationutils.currentanimationtimemillis ()-mstarttime);4     if(Timepassed <mduration) {5         Switch(mmode) {6              CaseScroll_mode:7                 Final floatx = minterpolator.getinterpolation (timepassed *mdurationreciprocal);8Mcurrx = Mstartx + math.round (x *mdeltax);9Mcurry = Mstarty + math.rounc (y *Mdeltay);Ten                  Break; One         ... A         } -     } -     return true; the}

The Mcurrx and Mcurry set in lines 8th and 9th above are the two parameters of the above Scrollto, indicating the target position of the slide. The Computescrolloffset method returns true to indicate that the slide process is not finished, otherwise the end is indicated.

From the above analysis, we probably understand the principle of scroller to achieve elastic sliding: Theinvaldate method will cause the View 's draw method to be called , and draw calls the computescroll method, thus overriding the computescroll method, and Computescrolloffset The method will dynamically calculate the distance for a very small period of time based on the passage of time. That is, one slide is split into countless small distances to slide to achieve "elastic sliding."

3. References

Explore the art of Android development

If there is unclear or inaccurate in the above narrative, I hope you will point out:

Several ways to implement view sliding in Android

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.