Several ways to implement view sliding in Android _android

Source: Internet
Author: User

What is view? What are the ways to achieve view sliding?
1. What we need to know about view

(1) What is view?

The view class in Android is the base class for all UI controls, which means that all the various UI controls that we normally get to, such as Button, Imagview, and so on, are inherited from the view class. The direct parent class of the layout manager, 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 a variety of appearances and behaviors. button, and so on, we can use it directly because Google has helped us complete the work of inheriting view and rewriting methods.

(2) Location of view

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

The ordinate of the upper left corner of Top:view, corresponding to the member variable mtop in the view class, can be obtained by the GetTop method;
The horizontal axis of the upper left corner of Left:view, corresponding to the member variable Mleft in the view class, can be obtained by the GetLeft method.
The ordinate of the lower right corner of the Bottom:view, corresponding to the member variable Mbottom in the view class, can be obtained by the Getbottom method;
The horizontal axis of the lower right corner of the Right:view, corresponding to the member variable mright in the view class, can be obtained by the GetRight method.
Note that the above coordinates 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 illustration:

With these four parameters, it is easy to calculate the width of the view: width = Right-left;height = Bottom-top. There are two parameters for view. Note: The Translationx represents the horizontal distance of the view translation, the translationy represents the vertical distance of the view translation, and x and y are the horizontal ordinate in the upper-left corner of the view. If the view is translated, the change is its x, Y (which represents the position of the top left corner of the current view), and its four positional parameters represent the original position information of the view and are always unchanged. View always satisfies the following relationships during translation:

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

2. Several ways to realize view sliding
in the process of using view, we often need to realize the sliding effect of view. such as ListView, follow the finger and move the custom view, and so on, the former slide effect is provided for us by the SDK, and for our custom view sliding effect needs our own to achieve. Here are a few ways to implement view sliding in detail below.

(1) using Scrollto/scrollby to implement view sliding

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

/** * Set The scrolled position of your view. 

 This would cause a call to * {@link #onScrollChanged (int, int, int, int)} and the view would be * invalidated.  * @param x The x position to scroll to * @param y the y position to scroll to */public void Scrollto (int x, int y) 
   {if (mscrollx!= x | | | mscrolly!= y) {int oldx = MSCROLLX; 
   int oldy = mscrolly; 
   MSCROLLX = x; 
   mscrolly = y; 
   Onscrollchanged (MSCROLLX, mscrolly, OLDX, Oldy); 
   if (!awakenscrollbars ()) {invalidate (); }}/** * 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. * @param x The amount of pixels to scroll by horizontally * @param y the amount of pixels to scroll by vertically/p 
ublic void Scrollby (int x, int y) {Scrollto (mscrollx + x, mscrolly + y); }

Through the 33~35 line of the above code we can see that the Scrollby method also calls the Scrollto method internally. In the above source we notice the MSCROLLX and mscrolly member variables, the former is the left edge of the view, minus the view's top edge minus the top edge of the view's content. The schematic diagram is as follows:

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

Through the above analysis, we understand that using the Scrollto/scrollby method to achieve view sliding is very simple and straightforward, then what is the price behind the simple? The price is that sliding is not "elastic", and elastic sliding refers to the view sliding should be a first acceleration and then gradually slowed down to stop the process, so that looks very smooth, not very abrupt. The Scrollto/scrollby method implementation of the sliding look will be very abrupt, such a user experience is not good. Before we solve this problem, let's look at other ways to implement view sliding.

(2) Use of animation to achieve view sliding

The use of animation to achieve view sliding mainly by changing the view of the Translationx and Translationy parameters to achieve, the advantage of using animation is that the sliding effect is smooth. As we mentioned above, the view's X and Y parameters determine the current position of the view, and by changing Translationx and translationy, we can change the current position of the view. We can use the property animation or motion tween to implement the view translation.

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

<?xml version= "1.0" encoding= "Utf-8"?> <set xmlns:android=
"http://schemas.android.com/apk/res/" Android "
 android:fillafter= true" >

 <translate
  android:duration= "MB"
  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 a motion tween to implement view sliding there 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 have moved it. Take the button for example, if we move a button through a motion tween, we will find that clicking on the screen in the original position of the button will strike the event, and clicking on the button on the move does not trigger the Click event.

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

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

The code above implements the use of property animation to translate the TargetView to the right in 100ms, 100px. The limitation of using property animations is that real property animations can only be used in Android 3.0+ (some Third-party libraries implement a compatible version of the properties of a low-level animation is not a real property animation), the advantage is that it can really move view rather than just move view image.

Through the above description, using property animation to achieve view sliding seems to be a good choice, and some view of the complex sliding effect only through animation can be more convenient to achieve.

(3) to realize the sliding of view by changing the layout parameters

The idea of sliding the view by changing the layout parameters is simple: for example, to move one view to the right, simply increase its marginleft parameter and move in the other direction, just change the corresponding margin parameter. Another way to beat the Bush is to put a view in front of the view you want to move (the initial width is set to 0). Then, for example, to move the view to the right, simply enlarge the preset view width so that the view is "squeezed" to the right. The code example is as follows:

Marginlayoutparams params = (marginlayoutparams) mbutton.getlayoutparams ();
Params.leftmargin + +;
Mbutton.requestlayout ();

The above code is achieved by sliding 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 achieve view sliding effect is not smooth, the good news is that we can use the Scroller method to assist the implementation of view elastic sliding. The usual code for using scroller to implement elastic sliding is as follows:

Scroller scroller = new Scroller (mcontext);

private void Smoothscrollto (int dstx, int dsty) {
 int scrollx = GETSCROLLX ();
 int delta = DSTX-SCROLLX;
 Scroller.startscroll (SCROLLX, 0, Delta, 0, 1000);
 Invalidate ();
}

@Override public
void Computescroll () {
 if (Scroller.computescrolloffset ()) {
  Scrollto ( Scroller.getcurrx (), Scroller.getcury ());
  Postinvalidate ();
 }


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

public void Startscroll (int startx, int starty, int dx, int dy, int duration) { 
 Mmode = Scroll_mode; 
 mfinished = false; 
 mduration = Duration; 
 Mstarttime = Animationutils.currentanimationtimemillis (); 
 Mstartx = StartX; 
 Mstarty = Starty; 
 MFINALX = startx + dx; 
 Mfinaly = Starty + dy; 
 Mdeltax = DX; 
 Mdeltay = dy; 
 Mdurationreciprocal = 1.0f/(float) mduration; 
 
 Mviscousfluidscale = 8.0f; 
 
 Mviscousfluidnormalize = 1.0f; 
 Mviscousfluidnormalize = 1.0f/viscousfluid (1.0f); 
}
 

From the above source 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 do you realize the slide of view? Let's go back to scroller idiomatic code. We see line 7th calling the Invalidate method, which requests redrawing view, which causes the view's draw method to be invoked, 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 arguments you get? These two parameters are set in the Computescrolloffset method called in line 12th, so let's look at the code that sets the two parameters in this method:

public Boolean Computescrolloffset () {
 ...
 int timepassed = (int) (Animationutils.currentanimationtimemillis ()-mstarttime);
 if (timepassed < mduration) {
  switch (mmode) {case
   Scroll_mode:
    final float x = Minterpolator.getinterpol ation (timepassed * mdurationreciprocal);
    Mcurrx = Mstartx + math.round (x * mdeltax);
    Mcurry = Mstarty + math.rounc (y * mdeltay);
    break;
  ...
  }
 }
 return true;
}

The Mcurrx and Mcurry set in lines 8th and 9th of the above code are the two parameters of the above Scrollto, representing the target position for this slide. The Computescrolloffset method returns true to indicate that the sliding process has not yet ended, or that it ends.

Through the above analysis, we probably understand the scroller to achieve the principle of elastic sliding: Invaldate method will cause the view of the draw method is called, and draw will invoke the Computescroll method, so rewrite the Computescroll method, The Computescrolloffset method dynamically calculates how much distance to slide over a very small period of time, based on the passage of time. That is, the first slide split into countless small distance sliding to achieve "elastic sliding."

Complete demo of all three sliding modes mentioned in this article

This is the entire content of this article, I hope to learn more about Android software programming help.

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.