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

Source: Internet
Author: User

Objective:

Just like the chat message list on mobile QQ. A portrait-sliding listview lists all messages, but each message can slide horizontally.

By default, there is only one place to digest touch events, or the ListView eats the event. The part that can be slid in the child item is eaten. The two clash with each other.


Do you think it's very divisive? The implementation is actually not complicated.
After understanding, it is convenient to extend to gridview,viewpager,scrollview and so on sliding 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 as the ListView item, which puts the message in the TextView. and a Delete button


The basic idea is:

Rewrite the item in the ListView, which is the Ontouchevent method of LinearLayout. To monitor horizontal and vertical sliding:

1) when sliding vertically. No matter

2) when sliding horizontally. Request the parent container, that is, the ListView does not intercept touch events, it is in the sub-view (that is, linearlayout) to handle it, when the horizontal touch time ends (motionevent.action_up) or the boundary ( Motionevent.action_cancel), restore the consent of the parent container to intercept touch events.


First on



The rewritten linearlayout such as the following:


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); Infer the threshold of the Traverse, in order to be compatible with devices of different sizes. In DP units Drag_x_throd = (int) typedvalue.applydimension (Typedvalue.complex_unit_dip, Context.getresources (). getDi Splaymetrics ()); 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 very important to request that the parent container be blocked from blocking touch events */public void Setparentintercepttouchevent (Boolean disallow) {viewparent PA Rent = GetParent (); if (parent! = null) {parent.requestdisallowintercepttouchevent (Disallow); }} Animator.animatorlistener Listener = new Animator.animatorlistener () {@Override public void Onani Mationstart (Animator Animator) {} @Override public void Onanimationend (Animator Animator) { Manimator = null; } @Override public void Onanimationcancel (Animator Animator) {manimator = null; } @Override public void Onanimationrepeat (Animator Animator) {}};}






Paste the specific calling code:

Activity_main.xml

<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>

Mainactivity.java

 
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; }    }}

Transferred from: http://blog.csdn.net/oyyj42/article/details/47333443

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

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.