Android imitation UC Browser left and right scrolling function (with source)

Source: Internet
Author: User

In this article, we want to add a text box to the right side of the slide menu and to scroll the text up and down. It is recommended to take a good look at the distribution mechanism of the Android touch event, which I will not talk about, and I'll just talk about the app. The functionality to be implemented is like a UC browser (or other mobile browser) scrolling left and right, switching pages, scrolling up and down, and dragging content.

Directory:

I. Functional REQUIREMENTS and implementation

Second, layout and code

Three, the principle and the explanation

the effect of this article: (source code download)



I. Functional REQUIREMENTS and implementation

1. Function Requirements:

(1) When the finger starts to move around the screen, only left and right scrolling menu, if the finger has been pressed, and moved up and down, then the menu display part remains unchanged, but the text box does not move up and down!

(2) When the finger starts to move up and down the screen, the text box can only scroll up and down, if the finger has been pressed, and move left and right, then the text box display part remains unchanged, but the menu does not move around!

2, the initial realization:

in the previous article, add a ListView for the left menu item, a textview for the content item on the right, and a scrollview for TextView to enable it to scroll up and down.

This effect is certainly not right, you see, we move the text on the top and bottom of the finger, if the left and right move, the menu is also displayed.



3. Modify the implementation

I wanted to start with the distribution of touch events here because I was registering the ScrollView touch event with LinearLayout. (The linearlayout contains the ScrollView, not the following layout), so the touch event is passed to LinearLayout first.

In the following two cases:

(1) If the finger moves around, the touch event is passed to LinearLayout. The function Ontouch returns True, indicating that the touch event is no longer being passed, so ScrollView cannot move.

(2) If the finger moves up and down, the touch event is passed to LinearLayout first, but LinearLayout does not do any processing and is passed directly to Scrollview,scrollview to handle the touch event.

This is the modified effect:


second, layout and code
1. Layout

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:id=" @+id/layout "android:layout_width=" match_parent "android:layout_height=" Ma Tch_parent "android:orientation=" Horizontal "tools:context=". Mainactivity "> <linearlayout android:id=" @+id/menu "android:layout_width=" Match_parent "and        roid:layout_height= "match_parent" android:orientation= "vertical" android:background= "@drawable/menu" > <!--Add a ListView control-<listview android:id= "@+id/menulist" android:layout_width = "Fill_parent" android:layout_height= "fill_parent"/> </LinearLayout> <linearlayo         UT android:id= "@+id/content" android:layout_width= "match_parent" android:layout_height= "Match_parent" android:orientation= "vertical" > <scrollview android:id= "@+id/scrollview" AndroiD:layout_width= "Fill_parent" android:layout_height= "wrap_content" > <textview android:id= "@+id/content _text "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:t ext= "@string/text1" android:textsize= "22px"/> </ScrollView> </LinearLayout> </linearlay Out>

2. Code

/** * @ author Lin Bingwen * @ time 2015.2.17 */package com.example.learningjava;import java.util.arraylist;import java.util.HashMap;imp Ort Java.util.map;import Com.example.learningjava.r.string;import Android. R.integer;import Android. R.menu;import Android.os.asynctask;import Android.os.build;import Android.os.bundle;import Android.annotation.suppresslint;import Android.annotation.targetapi;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.arrayadapter;import Android.widget.linearlayout.layoutparams;import Android.widget.listview;import Android.widget.ScrollView;import Android.widget.toast;import Android.app.activity;import Android.content.context;import Android.util.AttributeSet; Import Android.util.displaymetrics;import Android.util.log;import Android.view.gesturedetector;import Android.view.menu;import Android.view.motionevent;import Android.view.velocitytracker;import Android.view.View; Import Android.view.view.ontouchlistener;import AndroidOid.view.window;import Android.widget.linearlayout;public class Mainactivity extends Activity implements  Ontouchlistener{private linearlayout menulayout;//menu item Private linearlayout contentlayout;//content Item Private LayoutParams menuparams;//the parameters of the menu item private layoutparams contentparams;//The width value of the parameter contentlayout of the content item private int displaywidth;//  Phone screen resolution private float xdown;//finger point down the horizontal axis private float xmove;//finger movement of the horizontal axis private float xup;//record finger on the horizontal axis after lifting the private Float ydown;//Finger point down the ordinate private float ymove;//finger movement of the ordinate private velocitytracker mvelocitytracker;      Used to calculate the speed of finger slippage. Private float velocityx;//finger move around speed public static final int snap_velocity = 400;      When scrolling to show and hide the menu, the speed at which your finger slides needs to be reached. Private Boolean menuisshow = false;//Initialization menu item is not phoenixes private static final int menupadding=160;//menu complete display, left to content width private ListView menulistview;//The contents of the menu list private ScrollView scrollview;//the scroll bar of the text box private Boolean wanttoscrolltext=false;// Want to scroll down text content private Boolean Wanttoscrolltextmenu=false;private Boolean Onefucction=false;//ensure that the function is called only once protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate)        ;        Requestwindowfeature (Window.feature_no_title);        Setcontentview (R.layout.activity_main);        Initlayoutparams ();        Initmenulist ();    Initscrollview (); }/** * Initialize layout and set its corresponding parameters */private void Initlayoutparams () {//Get screen size displaymetrics dm = new Displaymetric      S ();        Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM);              Displaywidth =dm.widthpixels;      Get Control Menulayout = (linearlayout) Findviewbyid (R.id.menu);      Contentlayout = (linearlayout) Findviewbyid (r.id.content);            Findviewbyid (r.id.layout). Setontouchlistener (this);      Get control parameter menuparams= (linearlayout.layoutparams) menulayout.getlayoutparams ();             Contentparams = (linearlayout.layoutparams) contentlayout.getlayoutparams ();      Initialize menu and content width and margin menuparams.width = displaywidth-menupadding; Menuparams.lefTmargin = 0-menuparams.width;      Contentparams.width = Displaywidth;            contentparams.leftmargin=0;      Set parameter Menulayout.setlayoutparams (MENUPARAMS);    Contentlayout.setlayoutparams (Contentparams); }/** * Initialize menu List contents */private void Initmenulist () {final string[] STRs = new string[] {"1th java Overview", "chapter 2nd Understanding Object Oriented  "," chapter 3rd data types and Operators "," chapter 4th flow Control and Arrays "," chapter 5th Object-Oriented (upper) "};  Menulistview = (ListView) Findviewbyid (r.id.menulist); Menulistview.setadapter (New arrayadapter<string> (this,android. R.layout.simple_list_item_1, STRs));//For ListView Binding Adapter//Startup list Click to listen for event Menulistview.setonitemclicklistener (new ONITEMCL Icklistener () {@Overridepublic void Onitemclick (adapterview<?> arg0, View arg1, int arg2,long arg3) {Toast.makete  XT (Getapplicationcontext (), "You have selected" + strs[arg2], toast.length_short). Show ();   }      }); }/** * Initialize ScrollView */public void Initscrollview () {ScrollView = (ScrollView) This.findviewbyid (R.id.scrollview      ); Scrollview.setontOuchlistener (this);//A view that is bound to listen for a side-slip event, that is, sliding on the bound view to show and hide the left layout. This sentence is very important, do not set its touch event, to not swallow the layout of the Touch event} @Override public boolean OnTouch (View V, motionevent event) {Acquirevelocitytrac Ker (event);       if (Event.getaction () ==motionevent.action_down) {xdown=event.getrawx ();      Ydown=event.getrawy (); return false;      } else if (Event.getaction () ==motionevent.action_move) {if (Wanttoscrolltext)//current want to scroll to display the text return false;        XMOVE=EVENT.GETRAWX ();      Ymove=event.getrawy ();     if (menuisshow) {isscrolltoshowmenu ();     return true;        } if (!onefucction) {onefucction=true;      This if can only be called once if (Math.Abs (xdown-xmove) <math.abs (ydown-ymove)) {wanttoscrolltext=true;              return false; }} isscrolltoshowmenu (); } else if (Event.getaction () ==motionevent.action_up) {onefucction=false; if (wanttoscrolltext) {wanttoscrolltext=      False return false;      } xup=event.getrawx ();    Isshowmenu ();  Releasevelocitytracker ();          } else if (Event.getaction () ==motionevent.action_cancel) {releasevelocitytracker (); return false;        } return True;//false to pass the touch event to scroll}/** * Depending on the distance the finger presses, determine whether to scroll the Display menu */private void Isscrolltoshowmenu () {              int Distancex = (int) (xmove-xdown);        if (!menuisshow) {scrolltoshowmenu (DISTANCEX);        }else{Scrolltohidemenu (DISTANCEX);       }}/** * After lifting the finger to determine whether to display the menu */private void Isshowmenu () {Velocityx =getscrollvelocity ();       if (Wanttoshowmenu ()) {if (Shouldshowmenu ()) {ShowMenu ();       }else{Hidemenu ();       }} else if (Wanttohidemenu ()) {if (Shouldhidemenu ()) {Hidemenu ();   }else{ShowMenu (); }}}/** * Want to show menu when move right distance greater than 0 and menu not visible */private Boolean wanttoshowmenu () {return!menuisshow&&xup  -xdown>0; /** * Want to hide the menu when the left move distance is greater than 0 and the menu is visible */private Boolean wanttohidemenu () {return menuisshow&&xdown-xup>0; }/** * Determines that the menu should be displayed when the distance to the right is more than half of the menu or the speed exceeds the given value */private Boolean shouldshowmenu () {return xup-xdown>menuparams.width/ 2| |  velocityx>snap_velocity; }/** * Determines that the menu should be hidden when the left-moving distance exceeds half of the menu or the speed exceeds the given value */private Boolean shouldhidemenu () {return xdown-xup>menuparams.width/ 2| |  velocityx>snap_velocity;      }/** * Displays the menu bar */private void ShowMenu () {new Showmenuasynctask (). Execute (50);  Menuisshow=true;     }/** * Hides the menu bar */private void Hidemenu () {new Showmenuasynctask (). Execute (-50);  Menuisshow=false; /** * When the pointer is pressed, scrolling will slowly show the menu * @param scrollx the distance each scroll moves */private void Scrolltoshowmenu (int scrollx) {if (scrollx&gt  ; 0&&scrollx<= menuparams.width) Menuparams.leftmargin =-menuparams.width+scrollx;   Menulayout.setlayoutparams (Menuparams); /** * When the pointer is pressed, the scroll will slowly hide the menu * @param scrollx the distance each scroll moves * * * private void Scrolltohidemenu (int scrollx) {if (scrollx&gt ; =-menuparams.width&&scrollx<0) Menuparams.leftmargiN=SCROLLX;   Menulayout.setlayoutparams (Menuparams);    }/** * Creates a Velocitytracker object and joins the sliding events that touch the content interface into the Velocitytracker.        * @param event adds motionevent */private void Acquirevelocitytracker (final motionevent event) to Velocitytracker {        if (null = = Mvelocitytracker) {Mvelocitytracker = Velocitytracker.obtain ();    } mvelocitytracker.addmovement (event);    /** * Gets the speed at which the finger slides in the content interface.    * @return sliding speed, in units of how many pixels are moved per second.        */private int getscrollvelocity () {mvelocitytracker.computecurrentvelocity (1000);           int velocity = (int) mvelocitytracker.getxvelocity ();    return math.abs (velocity);            }/** * Releases Velocitytracker */private void Releasevelocitytracker () {if (null! = Mvelocitytracker) {            Mvelocitytracker.clear ();            Mvelocitytracker.recycle ();        Mvelocitytracker = null; }}/** *: Simulates the animation process so that the naked eye can see the effect of scrolling * */class Showmenuasynctask extends ASYNCTASK&LT;integer, Integer, integer> {@Override protected integer doinbackground (integer ... params) {          int leftMargin = Menuparams.leftmargin;              while (true) {//Scrolls the interface according to the incoming speed, and jumps out of the loop when scrolling reaches the left or right edge.              LeftMargin + = Params[0];                  if (Params[0] > 0 && leftMargin > 0) {leftmargin= 0;              Break } else if (Params[0] < 0 && leftMargin <-menuparams.width) {Leftmargin=-menuparam                  S.width;              Break              } publishprogress (LeftMargin);              try {thread.sleep (40);//sleep for the naked eye to see the scrolling effect} catch (Interruptedexception e)              {E.printstacktrace ();      }} return leftMargin;          } @Override protected void Onprogressupdate (Integer ... value) {menuparams.leftmargin = value[0]; MeNulayout.setlayoutparams (Menuparams);          } @Override protected void OnPostExecute (Integer result) {Menuparams.leftmargin = result;      Menulayout.setlayoutparams (Menuparams); }  }}


three, the principle and the explanation

Principle:

1. Register the ScrollView Touch event with the linearlayout. (The linearlayout contains the ScrollView, does not understand the layout)

2, first of all to determine whether the gesture is to move or move up and down, if it is left and right movement, then linearlayout get touch event, that is, function Ontouch return True, if you want to move up and down, that is, function Ontouch return false;

It is important to note that gestures are judged only once, what does it mean? That means you press it for the 1th time, until you press it, only to judge the movement you want to do with your gestures.

3, after the finger left the screen, then to restore all parameters.



Android imitation UC Browser left and right scrolling function (with source)

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.