Summary of several methods for smooth screen switching in Android

Source: Internet
Author: User

Articles that have been found for a long time

From: http://archive.cnblogs.com/a/2265135/

First: viewflipper + gesturedetector;

Second, rewrite the viewgroup to manage the view;

Third: Use the viewpager that comes with the system.

 

As for the first method, many people just talk about the idea: Use viewswitcher and add the animation effect.

For more information about the second method, see http://marshal.easymorse.com/archives/3828. here I have posted the following:

The above is the result of dragging your fingers. If you drag the screen over the midpoint, the system automatically moves to the second screen after you release the mouse. In addition, if you use a swipe gesture, you can automatically move the next screen.

 

I mainly refer to this project:

Http://code.google.com/p/andro-views/

There is source code, but his code has two problems:

  • There is a bug. in a specific situation, two screens may appear at the same time. Similar to the third figure above, it cannot be switched over. This may be caused by the author's missing touch status.
  • The code is complicated. The author estimates that the code is written by referring to the android source code. Some code is copied from the android code, such as viewgroup and scrollview.

Seeing Eric's implementation makes me understand that the previous animation processing and the method of modifying the blank edge (margin) are not the right path. The main path is scroller, which is a help class with animation support.

The basic idea of scroller is to arrange multiple sub-views horizontally to the layout (self-implemented layout) in this example. Then, scroller supports horizontal movement of the scroll bar in windows and is animated. For example, the scroller method:

  • Startscroll (INT startx, int starty, int dx, int Dy), set the start point and moving distance between the X axis and the Y axis. Call this method to perform a rolling animation. The animation duration is 250 milliseconds, you can also use another method of overloading to set the animation cycle.
  • Abortanimation
  • Computescroloffset (): determines whether to move to the specified position. It is called during the movement process. If it is not in place, it will continue to move to produce the animation movement effect. In this example, the computescroll method of viewgroup is overwritten, this method is called in

Call scroller in layout.

In Android, view has two subclasses: widget and viewgroup. widgets are visible window components, such as buttons, viewgroup is layout, and viewgroup has provided multiple layout subclasses, such as linearlayout.

In this example, the viewgroup subclass is implemented.

The onlayout method is used to horizontally arrange the child views:

@ Override
Protected void onlayout (Boolean changed, int left, int top, int right,
Int bottom ){
Log. D (TAG, "> left:" + Left + "Top:" + TOP + "Right:" + Right
+ "Bottom:" + bottom );

/**
* Set the layout and arrange the sub-views in horizontal order
*/
For (INT I = 0; I <getchildcount (); I ++ ){
View child = getchildat (I );
Child. setvisibility (view. Visible );
Child. Measure (right-left, bottom-top );
Child. layout (0 + I * getwidth (), 0, getwidth () + I * getwidth (),
Getheight ());

By overwriting the computescroll method, you can calculate the movement of the mobile screen and re-draw the screen:

@ Override
Public void computescroll (){
If (scroller. computescroloffset ()){
Scrollto (scroller. getcurrx (), 0 );
Postinvalidate ();
}
}

A method named scrolltoscreen is compiled to switch to the screen according to the specified screen number:

/**
* Switch to the specified Screen
*
* @ Param whichscreen
*/
Public void scrolltoscreen (INT whichscreen ){
If (getfocusedchild ()! = NULL & whichscreen! = Currentscreenindex
& Getfocusedchild () = getchildat (currentscreenindex )){
Getfocusedchild (). clearfocus ();
}

Final int Delta = whichscreen * getwidth ()-getscrollx ();
Scroller. startscroll (getscrollx (), 0, Delta, 0, math. Abs (DELTA) * 2 );
Invalidate ();

Currentscreenindex = whichscreen;
}

The snaptodestination method is used to process the processing after the screen is dragged to a position:

/**
* The number of screens to be switched is determined based on the current X coordinate position.
*/
Private void snaptodestination (){
Scrolltoscreen (getscrollx () + (getwidth ()/2)/getwidth ());
}

 

Then let's talk about how to handle the gesture event. Eric's implementation uses ontouch event processing, so the code is not concise. Because we need to record the historical data of many combined gestures, we must have some status bits and some coordinate values.

I used gesturedetector's gesture to process events to simplify this process, and only handled the outouchevent method in the handling of the gesture lift event.

 

For specific code, see: http://easymorse.googlecode.com/svn/tags/ScrollDemos-0.6/

 

Upgrade version:

On this basis, a version is implemented, which combines the page control effect. In addition, a form view is used to demonstrate the versatility of the solution.

Source code see: http://easymorse.googlecode.com/svn/tags/ScrollDemos-0.7/

 

The third method: see: http://blog.csdn.net/billpig/article/details/6650097

At first, I first came into contact with two screen switches: Innovation originated from imitation 3: switching between the two screens left and right. In this article, I would like to thank the author for providing such a good demo for us.

 

What is viewpager?


It is a class that enables smooth switching between the left and right screens. It is provided by Google and supplemented by Android. First, let everyone have an intuitive understanding.

 

When we search for related topics online, we will see many questions about this: how to smooth? Horizontal movement? And so on. Now, we can not do this laborious task by ourselves. We only need to use a class called viewpager. Viewpager was recently released in compatibility package. It supports Android 1.6 +. To use it, update compatibility through SDK manager.
Package, the specific use method in <sdk_doc_path>/SDK/compatibility-library.html (sdk_doc_path is the location of the built-in Android documentation, need to be updated to the latest documentation ).


Innovation comes from imitation 3: switching between the left and right screens. This provides a workspace for switching between the left and right screens. Now, this workspace class has been released on Google I/O, it is easy for us to use. I will release it together with the source code of this demo later. What is the difference between viewpager and workspace? Let's take a look at the API Doc statement:


Layout manager that allows the user to Flip left and right through pages of data. You supply an implementation ofPagerAdapterTo generate the pages that the view shows.


As mentioned above, viewpager provides an adapter for us to control various views, while workspace needs to be manually added, which is equivalent to a "static switch ". Next I will introduce how to use it:

1. Download the android SDK & AVD Manager Update: available packages-> Android repository-> Android compatibility package, revision 3. it will be installed in the \ extras \ Android \ Compatibility \ V4 File

2. Create an android project, add the android-support-v4.jar to the project under the above installation directory, if it is the latest ADT, just right-click the project-> Android tools-> Add compatibility Library

3. Use viewpager in Activity

4. If viewpager is defined in XML, write the global path, for example:

  1. <Android. Support. v4.view. viewpager
  2. Android: layout_width = "match_parent"
  3. Android: layout_height = "match_parent"
  4. Android: Id = "@ + ID/awesomepager"/>


5. Create a pageradapter and implement the following methods:

Getcount (), instantiateitem (), destroyitem (), isviewfromobject ().

As mentioned above, we have pasted the code and found that switching between the left and right screens can be implemented very quickly and easily.

  1. Public class awesomepageractivity extends activity {
  2. Private viewpager awesomepager;
  3. Private context cxt;
  4. Private awesomepageradapter awesomeadapter;
  5. Private layoutinflater minflater;
  6. Private list <View> mlistviews;
  7. /** Called when the activity is first created .*/
  8. @ Override
  9. Public void oncreate (bundle savedinstancestate ){
  10. Super. oncreate (savedinstancestate );
  11. Setcontentview (R. layout. Main );
  12. Cxt = this;
  13. Awesomeadapter = new awesomepageradapter ();
  14. Awesomepager = (viewpager) findviewbyid (R. Id. awesomepager );
  15. Awesomepager. setadapter (awesomeadapter );
  16. Mlistviews = new arraylist <View> ();
  17. Minflater = getlayoutinflater ();
  18. Mlistviews. Add (minflater. Inflate (R. layout. layout1, null ));
  19. Mlistviews. Add (minflater. Inflate (R. layout. layout2, null ));
  20. Mlistviews. Add (minflater. Inflate (R. layout. layout3, null ));
  21. }
  22. Private class awesomepageradapter extends pageradapter {
  23. @ Override
  24. Public int getcount (){
  25. Return mlistviews. Size ();
  26. }
  27. /**
  28. * Create a page from the specified position
  29. *
  30. * @ Param container viewpager container
  31. * @ Param position the page position to be instantiated.
  32. * @ Return returns the page with the specified position. It does not need to be a view or other view containers.
  33. */
  34. @ Override
  35. Public object instantiateitem (View Collection, int position ){
  36. (Viewpager) Collection). addview (mlistviews. Get (position), 0 );
  37. Return mlistviews. Get (position );
  38. }
  39. /**
  40. * <Span> destroy page from the specified position </span>
  41. *
  42. *
  43. * <Span> same as the preceding parameter </span>
  44. */
  45. @ Override
  46. Public void destroyitem (View Collection, int position, object view ){
  47. (Viewpager) Collection). removeview (mlistviews. Get (position ));
  48. }
  49. @ Override
  50. Public Boolean isviewfromobject (view, object ){
  51. Return view = (object );
  52. }
  53. @ Override
  54. Public void finishupdate (view arg0 ){}
  55. @ Override
  56. Public void restorestate (parcelable arg0, classloader arg1 ){}
  57. @ Override
  58. Public parcelable savestate (){
  59. Return NULL;
  60. }
  61. @ Override
  62. Public void startupdate (view arg0 ){}
  63. }
  64. }

In this way, we can easily switch between the two screens. The content on the specific page depends on everyone!

 

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.