Solutions for nesting sliding in different directions in Android (ListView as an example)

Source: Internet
Author: User
Tags gety

A list of chat messages like mobile QQ, a vertically sliding listview lists all messages, but each message can slide sideways.
Do you feel very divided? In fact, it is not complicated to realize.
After understanding, you can easily extend to the gridview,viewpager,scrollview and so on slide controls.

If you are unfamiliar with the andoroid touch event delivery process, see here:


For the simplest expression of the implementation method, I use a linearlayout for the ListView item, which puts the message TextView, and a Delete button


The main ideas are:

Rewrite the item in the ListView, which is the Ontouchevent method of LinearLayout, to listen for horizontal and vertical swipe:

1) When sliding vertically, no matter

2) when sliding horizontally, request the parent container, that is, the ListView does not intercept the touch event, itself in the sub-view (that is, linearlayout) inside the processing is good,

Recovery allows the parent container to intercept touch events when the cross-touch Time Ends (MOTIONEVENT.ACTION_UP) or outlines the boundary (Motionevent.action_cancel).


First on



The rewritten linearlayout are as follows:


Package Ex.oyyj.listviewfulldemo;import Android.animation.animator;import Android.animation.objectanimator;import Android.content.context;import Android.util.attributeset;import Android.util.log;import Android.util.TypedValue; Import Android.view.motionevent;import android.view.viewparent;import android.widget.linearlayout;/** * Created by Oyyj on 2015/8/6.    */public class Horizontalslidelayout extends LinearLayout {private static String TAG = "Verticalslidelayout";    private int drag_x_throd = 0;    private int scroll_x = 0;    Private final int anim_duration = 300;    private static final int slide_to_left =-1;    private static final int slide_to_right = 1;    private int mslidedirection = 0;        Public Horizontalslidelayout (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);  Determine the threshold of the cross, in order to be compatible with devices of different sizes, in DP units Drag_x_throd = (int) typedvalue.applydimension (Typedvalue.complex_unit_dip, 30, Context.getresources (). Getdisplaymetrics ()); scroll_x = (int) typedvalue.applydimension (Typedvalue.complex_unit_dip, Context.getresources ().    Getdisplaymetrics ());    } public Horizontalslidelayout (context context, AttributeSet Attrs) {This (context, attrs, 0);    Public Horizontalslidelayout (Context context) {This (context, NULL, 0);    } @Override protected void Onattachedtowindow () {Super.onattachedtowindow ();    } int downx, DownY;    Boolean isneedtogoback;    Private Objectanimator Manimator;        @Override public boolean ontouchevent (Motionevent ev) {Boolean isintercepthere = false; try {switch (ev.getaction ()) {Case MotionEvent.ACTION_DOWN:downX = (int) E                    V.getx ();                    DownY = (int) ev.gety ();                    Isintercepthere = true;                    if (manimator! = null) {Manimator.cancel ();                } break; Case MotionevEnt.                    Action_move:int dx = (int) math.abs (Ev.getx ()-DOWNX);                    int dy = (int) math.abs (ev.gety ()-DownY); if (dx > dy && dx > Drag_x_throd) {log.i (TAG, "Horizontal stroke!                       Intercept it ");                        Setparentintercepttouchevent (TRUE);                        Isintercepthere = true; Mslidedirection = (Ev.getx ()-Downx) > 0?                        Slide_to_right:slide_to_left;                            if (mslidedirection = = slide_to_left) {Isneedtogoback = true;                        Playanimation (scroll_x, anim_duration); } else if (mslidedirection = = Slide_to_right && isneedtogoback) {playanimation (0, ANIM                        _duration); }} else if (dy > dx) {log.i (TAG, "vertical stroke!                    Do not intercept ");                } break; Case Motionevent.action_up:case MotionEvent.ACTION_CANCEL:setParentInterceptTouchEvent (FALSE);                    Isintercepthere = false;                    Downx = 0;                    DownY = 0;            Break        }} catch (Exception e) {e.printstacktrace ();    } return isintercepthere; } private void Playanimation (int translationx, int duration) {if (manimator! = null) {Manimator.can        Cel ();        } Manimator = Objectanimator.ofint (This, "Scrollx", Translationx);        Manimator.setduration (duration);        Manimator.start ();    Manimator.addlistener (listener); }/* This function is important to request that the parent container be blocked from blocking touch events */public void Setparentintercepttouchevent (Boolean disallow) {viewparent par        ent = GetParent ();        if (parent! = null) {parent.requestdisallowintercepttouchevent (disallow);   }} Animator.animatorlistener Listener = new Animator.animatorlistener () {     @Override public void Onanimationstart (Animator Animator) {} @Override public void Onani        Mationend (Animator Animator) {manimator = null;        } @Override public void Onanimationcancel (Animator Animator) {manimator = null; } @Override public void Onanimationrepeat (Animator Animator) {}};}





Paste the detailed call code:


<relativelayout 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: paddingleft= "@dimen/activity_horizontal_margin"    android:paddingright= "@dimen/activity_horizontal_margin"    android:paddingtop= "@dimen/activity_vertical_margin"    android:paddingbottom= "@dimen/activity_vertical_ Margin "tools:context=". Mainactivity "    android:background=" #ffffff ">    <listview        android:layout_width=" Wrap_content "        android:layout_height= "wrap_content"        android:id= "@+id/listview"        android:divider= "@drawable/ Divider "        android:listselector=" @drawable/selector_list_background "        android:layout_centerinparent=" True "/></relativelayout>


Package Ex.oyyj.listviewfulldemo;import Android.app.activity;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.listview;import Android.widget.textview;public class MainActivity    Extends Activity {private ListView mlistview; string[] Films = new string[]{"Pancake Man", "Demon Hunter", "Sage return", "Taoist Mountain", "Dynasty woman    Yang "," Gardenia Flower Open "," Taiping Round (Down) ",};        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mlistview = (ListView) Findviewbyid (R.id.listview);        Final Titleadapter titleadapter = new Titleadapter (Layoutinflater.from (this), films);    Mlistview.setadapter (Titleadapter);        } private class Titleadapter extends Baseadapter {string[] itemnames;        Layoutinflater Inflater;Public Titleadapter (Layoutinflater _inflater, string[] names) {inflater = _inflater;        Itemnames = Names.clone ();        } @Override public Object getItem (int i) {return itemnames[i];        } @Override public long getitemid (int i) {return i;        } @Override public int getcount () {return itemnames.length; } @Override public View getView (int i, view view, ViewGroup ViewGroup) {try {Vie                Wholder holder = new Viewholder ();                    if (view = = null) {view = Inflater.inflate (R.layout.item_layout, ViewGroup, false);                    Holder.title = (TextView) View.findviewbyid (R.id.item);                View.settag (holder);                } else {holder = (Viewholder) view.gettag (); } if (Holder! = NULL && Holder.title! = null) {TextvieW TV = Holder.title;                Tv.settext (Itemnames[i]);            }} catch (Exception e) {e.printstacktrace ();        } return view;        } private class Viewholder {TextView title; }    }}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Solutions for nesting sliding in different directions in Android (ListView as an example)

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.