The key points of realizing right sliding destroy function in Android app _android

Source: Internet
Author: User
Tags abs

Today to bring you a right to slide the effect of destruction activity, activtiy with the movement of the fingers moved, the effect is still relatively rare in Android applications, in iOS is more common, such as "NetEase News", "Food Jay", "Taobao" and other applications such as the effect , and the Android application "Know" is also the effect of this sliding switching activity, but I found that "Taobao" has not moved with the movement of gestures, but only to capture the sliding gesture, and then produce a smooth switch interface animation effect, this is still very good in Android to achieve,   Online A lot of sliding switch activity demo seems to be the effect of it, if you want to achieve a similar "NetEase news" of the potential sliding and sliding, it seems to be more complicated, I previously saw in ios "NetEase News" of this effect is very interesting, And then a group of friends asked me how to achieve a sliding switch effect like "knowing" this application, I also deliberately went to a "know", in the previous implementation I encountered a number of bottlenecks, did not realize out of the shelve there, today inadvertently to the activity set transparent background, so I suddenly realized that, Really inspiration from the moment, can not be forced ah, and then their own to achieve this effect out, to share with you, hope to have this need you a little help.
Not sure you are familiar with the use of the Scroller class and View Scrollby () and Scrollto ()? I've introduced the principle of sliding implementation of scroller. Android takes you from the source point of view to analyze the scroller of the rolling principle, where also introduced Scrollby () and Scrollto () method, do not understand the students can go to see, This is a great help for achieving this effect, and friends with Scrollby () and Scrollto () should know that if you want to scroll for a view (such as a button), we call the Scrollby () method of that view (button) directly, Instead of scrolling through the view (button), the contents of the view (the text on the button) are scrolled, so if we want the view to scroll as a whole, we need to call the Scrollby () method on the parent layout of its view, and return to this article. If we want to scroll through an activity, we need to scroll the parent layout of the top-level layout of this activity layout file
For example, the following XML layout file

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" 
  xmlns:tools= "http:// Schemas.android.com/tools " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent " 
  android:gravity= "center" 
  android:orientation= "vertical" > 
 
 
</LinearLayout> 

If we scroll to linearlayout and we don't achieve what we want, we can only scroll through the contents of the LinearLayout or the child view, so we need to get getparent using LinearLayout () method to get the parent layout, the Android system actually sets a framelayout to the outermost layer of our layout file, so we actually just scroll the framelayout.
After understanding the principle of implementation, we will write code, first new Android project, named Sildingfinish
Since our requirements may not be an interface to provide the effect of this sliding switch, so we should take this part of the sliding logic out, I have here he wrote an extension relativelayout custom layout sildingfinishlayout, first we look at its code

Package Com.example.view; 
Import Android.content.Context; 
Import Android.util.AttributeSet; 
Import android.view.MotionEvent; 
Import Android.view.View; 
Import Android.view.View.OnTouchListener; 
Import android.view.ViewConfiguration; 
Import Android.view.ViewGroup; 
Import Android.widget.AbsListView; 
Import Android.widget.RelativeLayout; 
Import Android.widget.ScrollView; 
 
Import Android.widget.Scroller; /** * Custom Sliding relativelayout, similar to iOS sliding delete page effect, when we want to use * This feature, we need to set the top-level layout of the activity to Sildingfinishlayout, * and then need to call Setto Uchview () method to set the view * * @author xiaanming * * * * @blog http://blog.csdn.net/xiaanming * */public class Sild 
  Ingfinishlayout extends Relativelayout implements Ontouchlistener {/** * sildingfinishlayout layout's parent layout * * 
  Private ViewGroup Mparentview; 
  /** * Handle sliding logic View/private view touchview; 
  /** * Sliding minimum distance */private int mtouchslop; 
  /** * Press the point of the x coordinate * * * private int downx; /** * Press the y-coordinate of the point 
   * * private int downY; 
  /** * Temporary storage x Coordinate * * * private int tempx; 
  /** * Sliding class * * private scroller Mscroller; 
  /** * sildingfinishlayout Width * * private int viewwidth; 
   
  /** * record is sliding * * Private Boolean issilding; 
  Private Onsildingfinishlistener Onsildingfinishlistener; 
   
 
  Private Boolean isfinish; 
  Public Sildingfinishlayout (context, AttributeSet attrs) {This (context, attrs, 0); Sildingfinishlayout (context, AttributeSet attrs, int defstyle) {Super (context, Attrs, Defstyle 
 
    ); 
    Mtouchslop = Viewconfiguration.get (context). Getscaledtouchslop (); 
  Mscroller = new Scroller (context);  @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {super.onlayout (changed, L, 
    T, R, b); 
      if (changed) {//Gets the parent layout of the sildingfinishlayout layout Mparentview = (viewgroup) this.getparent (); 
    Viewwidth = This.getwidth (); 
 
} 
  }  /** * Set Onsildingfinishlistener, in Onsildingfinish () method Finish Activity * * @param onsildingfinishlistener */public void Setonsildingfinishlistener (Onsildingfinishlistener onsildingfinishlistener) {This.onsildi 
  Ngfinishlistener = Onsildingfinishlistener; /** * Set Touch View * * @param touchview/public void Settouchview (view touchview) {this. 
    Touchview = Touchview; 
  Touchview.setontouchlistener (this); 
  Public View Gettouchview () {return touchview; /** * rolling out interface/private void Scrollright () {final int delta = (viewwidth + MPARENTVIEW.GETSCROLLX () 
    ); Call the Startscroll method to set some scrolling parameters, we call Scrollto in the Computescroll () method to scroll the item mscroller.startscroll (MPARENTVIEW.GETSCROLLX 
    (), 0,-delta + 1, 0, Math.Abs (delta)); 
  Postinvalidate (); 
    /** * Scroll to start position/private void Scrollorigin () {int delta = MPARENTVIEW.GETSCROLLX (); Mscroller.startscroll (MPARENTVIEW.GETSCROLLX (), 0,-delta, 0, Math.Abs (delta)); 
  Postinvalidate (); /** * Touch View is Abslistview, such as ListView, GridView and other subclasses * * @return/private Boolean Istoucho 
  Nabslistview () {return touchview instanceof Abslistview? true:false; /** * Touch view is ScrollView or its subclass * * @return/private Boolean Istouchonscrollview () {R Eturn touchview instanceof ScrollView? 
  True:false; @Override public boolean Ontouch (View v., motionevent event) {switch (event.getaction ()) {case Motion 
      Event.ACTION_DOWN:downX = TEMPX = (int) event.getrawx (); 
      DownY = (int) Event.getrawy (); 
    Break 
      Case MotionEvent.ACTION_MOVE:int MoveX = (int) event.getrawx (); 
      int deltax = Tempx-movex; 
      TEMPX = MoveX;  if (Math.Abs (MOVEX-DOWNX) > Mtouchslop && math.abs ((int) Event.getrawy ()-DownY) < Mtouchslop) {issilding =True 
          If the Touchview is Abslistview,//Then when the fingers slip, cancel item Click event, otherwise we slide also accompany item Click event Occurrence if (Istouchonabslistview ()) { 
          Motionevent CancelEvent = Motionevent.obtain (event); CancelEvent setaction (Motionevent.action_cancel | 
          (Event.getactionindex () << motionevent.action_pointer_index_shift)); 
        V.ontouchevent (CancelEvent); 
 
        } if (movex-downx >= 0 && issilding) {Mparentview.scrollby (deltax, 0); Shielding in the course of the slide ListView ScrollView such as their own sliding event if (Istouchonscrollview () | | Istouchonabslistview ()) {Retu 
        RN true; 
    }} break; 
      Case MotionEvent.ACTION_UP:isSilding = false; 
        if (MPARENTVIEW.GETSCROLLX () <=-viewwidth/2) {isfinish = true; 
      Scrollright (); 
        else {scrollorigin (); 
      Isfinish = false; 
    } break; //If the touch view is ABSLIstview or ScrollView After we have processed the above own logic//and then give it to Abslistview, ScrollView to handle its own logical if (Istouchonscrollview () | | istoucho 
    Nabslistview ()) {return v.ontouchevent (event); 
  //Other case directly returns true return true; The Scroller.computescrolloffset () returns True when @Override public void Computescroll () {//Call Startscroll, if (m 
      Scroller.computescrolloffset ()) {Mparentview.scrollto (Mscroller.getcurrx ()), Mscroller.getcurry ()); 
 
      Postinvalidate (); if (mscroller.isfinished ()) {if (Onsildingfinishlistener!= null && isfinish) {ONSILDINGFI 
        Nishlistener.onsildingfinish (); 
  Public interface Onsildingfinishlistener {public void onsildingfinish (); 

 } 
 
}

We use the GetParent () method in the OnLayout () method to get the parent layout of the layout and to get the width of its controls, primarily to prepare for the subsequent implementation.
Our sliding logic is mainly implemented using the view's Scrollby () method, the Scrollto () method, and the Scroller class, and when we drag the view, we listen for the distance of the finger on the screen and use the view's Scrollby () Method allows the view to slide with the fingers, and when the finger leaves the screen, we use the Scroller class Startscroll () method to set the sliding parameters, and then scroll according to the scrollto of the view.
for view sliding, there are some problems with touch event consumption, so we need to be familiar with the whole touch event of the view, the main thing is that there are some ListView, GridView, ScrollView and other controls in the activity. , if we have ListView, GridView, and other controls in the activity, we have no effect on the outermost layout of the event, because touch events are consumed by ListView, GridView and other controls. So the outermost layout of the activity does not get the touch of the event, and can not reach the logic, so in order to solve this touch event problem I provide Settouchview (View Touchview) method, This approach is to dynamically set the touch event to the view, so for the above problem, we set the Ontouchlistener directly to the ListView, the GridView, This avoids the problem of touch events in the outermost layer of the activity.

Next look at the Ontouch () method
First, we action_down record the x,y coordinates of the point
and then judge in Action_move, If the distance we slide horizontally is greater than mtouchslop and the distance in the vertical direction is less than mtouchslop, indicating that the activity is in a sliding state, we judge if Touchview is ListView, GridView, or its subclasses, Because we have fingers on the ListView, the GridView, along with the item click event, so we touchview set Action_cancel to cancel the item click event, and then the layout of the parent layout call Scrollby () To cancel the ScrollView event of Abslistview or Action_move itself if the Touchview is Abslistview or ScrollView returns true directly. The most intuitive feeling is that when we slide the activity, we prohibit abslistview or scrollview from sliding up and down
Finally, in action_up, if the finger slides more than one-second of the length of the control, the activity slides out of the interface , or slide to the starting position, we use the Scroller class's Startscroll () method to set the start position, slide the distance and the time, and then invoke the Postinvalidate () refresh interface, and then to the Computescroll () method, We use the Scrollto () method to scroll the parent layout of the layout, after scrolling, we determine whether the interface is sliding out of the interface, if it is to call the Onsildingfinishlistener interface Onsildingfinish () method, So as long as in the Onsildingfinish () method finish the interface is OK
The entire sliding layout of the code is this way, then we will use, the main interface activity only three buttons, jump to the normal layout of the activity, There are listview activity and scrollview activity in the

 <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" xmlns: tools= "Http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "Match_parent" "android:gravity=" center "android:orientation=" vertical "> <button android:id=" @+id/normal_activity  
 
  "Android:layout_width=" match_parent "android:layout_height=" wrap_content "android:text=" ordinary Activity "/> <button android:id= "@+id/abslistview_activity" android:layout_width= "Match_parent" Android:layout_ height= "Wrap_content" android:text= "Abslistview activity"/> <button android:id= "@+id/scrollview_act Ivity "android:layout_width=" match_parent "android:layout_height=" Wrap_content "android:text=" has a ScrollView Ctivity "/> </LinearLayout> 

&NBSP
Then the code of the Mainactivity, instantiate the button based on the ID, then set the Onclicklistener event for the button, the different buttons to jump to a different activity, and then set the animation to slide from right to left, Rewrite the onbackpressed () method to add animation from left to right when we press the return key of the mobile phone's physical keyboard

Package com.example.slidingfinish; 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.view.Window; 
 
Import Android.widget.Button; 
 
Import COM.EXAMPLE.SLIDINGFINISH.R; public class Mainactivity extends activity implements Onclicklistener {@Override protected void onCreate (Bundle s 
    Avedinstancestate) {requestwindowfeature (window.feature_no_title); 
    Super.oncreate (savedinstancestate); 
 
    Setcontentview (R.layout.activity_main); 
    Button Mbuttonnormal = (button) Findviewbyid (r.id.normal_activity); 
 
    Mbuttonnormal.setonclicklistener (this); 
    Button Mbuttonabs = (button) Findviewbyid (r.id.abslistview_activity); 
 
    Mbuttonabs.setonclicklistener (this); 
    Button Mbuttonscroll = (button) Findviewbyid (r.id.scrollview_activity); 
 
  Mbuttonscroll.setonclicklistener (this); 
 @Override public void OnClick (View v) {   Intent mintent = null;  
      Switch (V.getid ()) {Case r.id.normal_activity:mintent = new Intent (mainactivity.this, Normalactivity.class); 
    Break 
      Case r.id.abslistview_activity:mintent = new Intent (mainactivity.this, Absactivity.class); 
    Break 
      Case r.id.scrollview_activity:mintent = new Intent (mainactivity.this, Scrollactivity.class); 
    Break 
    } startactivity (Mintent); 
  Overridependingtransition (r.anim.base_slide_right_in, R.anim.base_slide_remain);  
    }//press the "Back" button in mobile phone @Override public void onbackpressed () {super.onbackpressed (); 
  Overridependingtransition (0, r.anim.base_slide_right_out); 
 } 
 
}

Here I posted code containing ListView activity, first look at the layout, our custom sliding layout sildingfinishlayout should be placed at the top of the XML

<?xml version= "1.0" encoding= "UTF-8"?> <com.example.view.sildingfinishlayout xmlns:android= 
"http://" Schemas.android.com/apk/res/android " 
  xmlns:tools=" Http://schemas.android.com/tools " 
  android:id=" @+id/ Sildingfinishlayout " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent 
  " android:background= "#556677" > 
 
  <listview 
    android:id= "@+id/listview" 
    android:cachecolorhint= "@ Android:color/transparent " 
    android:layout_width=" match_parent " 
    android:layout_height=" Match_parent " > 
  </ListView> 
   
   
</com.example.view.SildingFinishLayout> 

Package com.example.slidingfinish; 
Import java.util.ArrayList; 
 
Import java.util.List; 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.Window; 
Import Android.widget.AdapterView; 
Import Android.widget.AdapterView.OnItemClickListener; 
Import Android.widget.ArrayAdapter; 
 
Import Android.widget.ListView; 
Import COM.EXAMPLE.SLIDINGFINISH.R; 
Import Com.example.view.SildingFinishLayout; 
 
Import Com.example.view.SildingFinishLayout.OnSildingFinishListener; 
 
  public class Absactivity extends activity {private list<string> List = new arraylist<string> (); 
    @Override protected void OnCreate (Bundle savedinstancestate) {requestwindowfeature (window.feature_no_title); 
    Super.oncreate (savedinstancestate); 
 
    Setcontentview (R.layout.activity_abslistview); 
    for (int i = 0; I <= i++) {list.add ("test data" + i); } ListView Mlistview = (listvieW) Findviewbyid (R.id.listview); arrayadapter<string> adapter = new Arrayadapter<string> (Absactivity.this, Android. 
    R.layout.simple_list_item_1, list); 
 
    Mlistview.setadapter (adapter); 
    Sildingfinishlayout msildingfinishlayout = (sildingfinishlayout) Findviewbyid (r.id.sildingfinishlayout); 
          Msildingfinishlayout. Setonsildingfinishlistener (New Onsildingfinishlistener () {@Override 
          public void Onsildingfinish () {AbsActivity.this.finish (); 
 
    } 
        }); 
 
    Touchview to be set to ListView above Msildingfinishlayout.settouchview (Mlistview); Mlistview.setonitemclicklistener (New Onitemclicklistener () {@Override public void Onitemclick (Adapterview <?> Parent, view view, int position, long id) {startactivity (new Intent (Absactivity.this, Nor 
        Malactivity.class)); Overridependingtransition (r.anim.base_slide_right_in, R.anim.base_sliDe_remain); 
  } 
    }); 
    //Press the Back button in mobile phone @Override public void onbackpressed () {super.onbackpressed (); 
  Overridependingtransition (0, r.anim.base_slide_right_out); 
 } 
 
}

Using the ID to find the Sildingfinishlayout instance, using the Settouchview () method to set Touchview to ListView, Then call Setonsildingfinishlistener () set Onsildingfinishlistener, in Onsildingfinish () finish the interface is OK.
Before running the project, there is a very important operation, but also before I was stuck to the problem is that we need to set the activity to transparent, that is, set the theme Android:theme= "@android: Style/theme.translucent"

<activity 
      android:name= ". Absactivity " 
      android:theme=" @android: Style/theme.translucent "> 
    </activity> 
    <activity 
      android:name= ". Normalactivity " 
      android:theme=" @android: Style/theme.translucent "> 
    </activity> 
    < Activity 
      android:name= ". Scrollactivity " 
      android:theme=" @android: Style/theme.translucent "> 
    


Okay, now we can run the project and see how it works.

The

is exactly what we want, and if you want to add a sliding interface to the effect of just three steps, first change the outermost layer of the activity layout to sildingfinishlayout, and then call Settouchview in the activity () method to set the Touchview, set the Onsildingfinishlistener listener to finish the interface in the Onsildingfinish () method, Is it convenient to set the background of the activity to be transparent (not to set the topmost layout background color of the activity layout file to be transparent?) Well, today's explanation is over here. ~

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.