Android Imitation UC Browser up and down scrolling function _android

Source: Internet
Author: User
Tags abs

In this paper, we will add a text box to the right side of the Sideslip menu, and can make the text slide up and down and the menu scroll. It is recommended that you take a good look at the distribution mechanism of the Android touch event, which I will not elaborate on, and I'll just talk about the application. The functionality to be implemented is like a UC browser (or other mobile browser) scrolling around, switching pages, scrolling up and down, dragging content.
The effect of this article:

I. Functional REQUIREMENTS and implementation
1, functional requirements:
(1) When the finger began to move around the screen, can only be left and right scrolling menu, if the finger has been pressed, and moved up and down, then the menu Display section remains unchanged, but the text box does not move up and down!
(2) When the finger began to move up and down the screen, can only scroll up and down the text box, if the finger has been pressed, and moved around, then the text box to show the part of the same, but the menu is not moving around!
2. Preliminary realization:
The menu item on the left adds a ListView, adding a TextView to the content item on the right, and a scrollview for TextView to enable it to scroll up and down.
This effect is definitely wrong, you see, our fingers up and down to move the text, if it is still moving around, the menu is also displayed.

3, modify the implementation
At this point I wanted to start with the distribution of touch events, because I was registering the ScrollView touch event to LinearLayout. (LinearLayout contains ScrollView, do not understand the layout below), so touch events will first pass to LinearLayout.
The following two kinds of situations are divided:
(1) If the finger is moving around, the touch event is passed to LinearLayout. Function Ontouch Returns True, indicating that the touch event is no longer passed, so the ScrollView can't move.
(2) If the fingers move up and down, touch events first to LinearLayout, but linearlayout do not do any processing, directly passed to the Scrollview,scrollview to deal with touch events.
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=" Match_parent "android:orientation=" Horizontal "tools:context=". Mainactivity "> <linearlayout android:id=" @+id/menu "android:layout_width=" Match_parent "Android:layout_h" eight= "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> <linearlayout 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:text= "@string/text1" android:textsize= "22px"/> </ScrollView> </LinearLayout> </lin  Earlayout>

2, code

Package Com.example.learningjava; 
Import java.util.ArrayList; 
Import Java.util.HashMap; 
Import 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 Android.view.Window; 
 
Import Android.widget.LinearLayout; public class Mainactivity extends activity implements ontouchlistener{private LinearLayout menulayout;//menu item privat E linearlayout contentlayout;//content items Private layoutparams menuparams;//menu item Parameters private Layoutparams contentparams;//content Item Parameter contentlayout width value private int displaywidth;//Mobile screen resolution private float xdown;//finger point down the horizontal axis private float xmove;//finger move Movement of the horizontal axis private float xup;//record the horizontal axis of the finger on the point of private float ydown;//finger down the ordinate private float ymove;//finger movement ordinate private Ve Locitytracker Mvelocitytracker; 
 Used to calculate the speed at which a finger slides. Private float velocityx;//fingers move around the speed of public static final int snap_velocity = 400; 
 
 When scrolling shows and hides the menu, the speed at which the finger slides needs to be reached. Private Boolean menuisshow = false;//initialization menu item not 翙 private static final int menupadding=160;//menu complete display, left content for width pri Vate ListView the contents of the menulistview;//menu list private scrollview scrollview;//text box scroll bar private Boolean wanttoscrolltext=false;/ /want to scroll down the 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 (); /** * Initializes the layout and sets its corresponding parameter/private void Initlayoutparams () {//Gets the size of the screen displaymetrics DM = new Displaymet 
  RICS (); 
  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); 
  Gets the control parameter menuparams= (linearlayout.layoutparams) menulayout.getlayoutparams (); 
  
  Contentparams = (linearlayout.layoutparams) contentlayout.getlayoutparams (); 
  Initialize menu and content width and margins 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 content/private void Initmenulist () {final string[] STRs = new string[] {"1th Chapter Java Overview", "chapter 2nd Understanding 
  Object-Oriented ", 3rd Chapter data types and Operators", "4th Chapter Process Control and Array", "5th Chapter Object Oriented (above)"}; 
  Menulistview = (ListView) Findviewbyid (r.id.menulist); Menulistview.setadapter (New arrayadapter<string> (this,android). R.layout.simple_list_item_1, STRs))//Start list for ListView binding Adapter//Launch lists click on the Listener event Menulistview.setonitemclicklistener (new Onitemclicklistener () {@Override public void Onitemclick (adapterview<?> arg0, View arg1, int arg2,long arg3 
     
   {Toast.maketext () (Getapplicationcontext (), "You have selected + Strs[arg2], toast.length_short)." Show (); 
   
 } 
  }); }/** * Initialization scrollview/public void Initscrollview () {ScrollView = (ScrollView) This.findviewbyid (r.id.scrollvIew); Scrollview.setontouchlistener (this);//bind monitor the view of the Sideslip event, that is, to slide the bound view to show and hide the left layout. This sentence is very important not to set its touch event anymore, to not swallow the layout of the Touch event} @Override public boolean Ontouch (View V, motionevent event) {Acquireveloc 
  Itytracker (event); 
   if (Event.getaction () ==motionevent.action_down) {xdown=event.getrawx (); 
   Ydown=event.getrawy (); 
  return false; 
   else if (event.getaction () ==motionevent.action_move) {if (Wanttoscrolltext)//currently wants to scroll the display text return false; 
   XMOVE=EVENT.GETRAWX (); 
   Ymove=event.getrawy (); 
    if (menuisshow) {isscrolltoshowmenu (); 
   return true; 
   } if (!onefucction) {onefucction=true; 
    This if can only be invoked 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; 
  The touch event can then be passed back to the scroll}/** * Depending on the distance the finger is pressed, whether to scroll the display menu/private void Isscrolltoshowmenu (True;//false) {  
  int Distancex = (int) (xmove-xdown); 
  if (!menuisshow) {scrolltoshowmenu (DISTANCEX); 
  }else{Scrolltohidemenu (DISTANCEX); 
  }/** * Fingers raised 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 display the menu, when moving the distance to the right is greater than 0 and the menu is not visible/private Boolean Wanttoshowmenu () {return!menuisshow&&xup- 
 xdown>0; /** * Want to hide the menu, when moving the distance to the left is greater than 0 and the menu is visible/private Boolean Wanttohidemenu () {return menuisshow&&xdown-xup>0; /** * Judge should display the menu, when the right to move more than half of the menu or faster than the given value of the specified * * Private Boolean Shouldshowmenu () {return xup-xdown>menuparams.wi dth/2| | 
 velocityx>snap_velocity; /** * Judge should hide menu, when moving left more than half of the menu or faster than the given value/private Boolean Shouldhidemenu () {return xdown-xup>menuparams.wi dth/2| | 
 velocityx>snap_velocity; 
  /** * Displays the menu bar */private void ShowMenu () {new Showmenuasynctask (). Execute (50); 
 Menuisshow=true; 
  /** * Hide Menu bar/private void Hidemenu () {new Showmenuasynctask (). Execute (-50); 
 Menuisshow=false; /** * When the * pointer is pressed, scroll to show the menu slowly * @param scrollx the distance of each scrolling move * * private void Scrolltoshowmenu (int scrollx) {if Scrol 
  lx>0&&scrollx<= menuparams.width) Menuparams.leftmargin =-menuparams.width+scrollx; 
 Menulayout.setlayoutparams (Menuparams); /** * When the * pointer is pressed, scroll to hide the menu slowly * @param scrollx the distance per scrolling move/private void Scrolltohidemenu (int scrollx) {if Scrol Lx>=-menuparams.width&&scrollx<0) Menuparams.leftmargin=scrollx; 
 Menulayout.setlayoutparams (Menuparams); 
 /** * Creates the Velocitytracker object and joins the sliding event of the touch content interface into the Velocitytracker. * @param event to velocitytracker add motionevent */private void Acquirevelocitytracker (final motionevent event) {if (n 
  ull = = mvelocitytracker) {Mvelocitytracker = Velocitytracker.obtain (); 
 } mvelocitytracker.addmovement (event); 
 /** * Gets the speed at which the finger slides at the content interface. 
 * @return sliding speed, the number of pixels moved per second in units. 
  * * Private int getscrollvelocity () {mvelocitytracker.computecurrentvelocity (1000); 
  
  int velocity = (int) mvelocitytracker.getxvelocity (); 
 return math.abs (velocity); /** * Free Velocitytracker * * private void Releasevelocitytracker () {if (null!= mvelocitytracker) {Mveloci 
   Tytracker.clear (); 
   Mvelocitytracker.recycle (); 
  Mvelocitytracker = null; }/** * *: Simulate the animation process, so that the naked eye can see the effect of scrolling * */class Showmenuasynctask extends Asynctask<integer, Integer, INTEGER&G 
 T {
 
  @Override protected integer doinbackground (integer ... params) {int leftMargin = Menuparams.leftmargin; 
    while (true) {//scroll the interface according to the incoming speed, and jump out of the loop when the scroll 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=-menuparams.width; 
    Break 
    } publishprogress (LeftMargin); try {thread.sleep (40);//Hibernate, the naked eye can see 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);  } 
 
 } 
}

Iii. Principles and explanations
principle:
1, the ScrollView of the touch event registered to the LinearLayout. (LinearLayout contains ScrollView, do not understand the layout)
2, the first to determine whether the gesture is to move around or up and down movement, if it is left and right movement, then linearlayout get touch events, that is, the function Ontouch return true, if you want to move up and down, that function Ontouch return false;
Notice here that the gesture is judged only once, what does it mean? It means that the 1th time you press, until you have been pressed, this is only one time to judge your gestures want to do the exercise.
3, after the finger left the screen, then to restore all the parameters.

This is for everyone to share the source code, please download:Android Imitation UC browser up and down scrolling function , I hope this article will help you learn the Android software programming.

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.