ListView Example of horizontal sliding (horizontal sliding) in Android _android

Source: Internet
Author: User

The use of horizontal Listview-horizontallistview

Android ListView The default is vertical sliding, due to the requirements of the project, the need for ListView is horizontal sliding. There are many ways to do it, but one of the better ways is to encapsulate a control by itself, using the same way as ListView. Need to improve the place: get to the size of the picture is not processed. The original size of the picture is displayed on the interface. In order to better display the effect, should be compressed into a uniform size.

The Horizontallistview.java code is as follows:

/** * Transverse ListView * * * * @author SCD * */public class Horizontallistview extends Adapterview<listadapter> {
  public Boolean Malwaysoverridetouch = true;
  protected ListAdapter Madapter;
  private int mleftviewindex =-1;
  private int mrightviewindex = 0;
  protected int mcurrentx;
  protected int mnextx;
  private int mmaxx = Integer.max_value;
  private int mdisplayoffset = 0;
  protected Scroller Mscroller;
  Private Gesturedetector mgesture;
  Private queue<view> Mremovedviewqueue = new linkedlist<view> ();
  Private Onitemselectedlistener monitemselected;
  Private Onitemclicklistener monitemclicked;
  Private Onitemlongclicklistener monitemlongclicked;

  Private Boolean mdatachanged = false;
    Public Horizontallistview (context, AttributeSet attrs) {Super (context, attrs);
  Initview ();
    Private synchronized void Initview () {mleftviewindex =-1;
    Mrightviewindex = 0;
    Mdisplayoffset = 0;
    Mcurrentx = 0; MNEXTX = 0;
    Mmaxx = Integer.max_value;
    Mscroller = new Scroller (GetContext ());
  Mgesture = new Gesturedetector (GetContext (), mongesture); @Override public void Setonitemselectedlistener (Adapterview.onitemselectedlistener listener) {Monitemse
  lected = listener; @Override public void Setonitemclicklistener (Adapterview.onitemclicklistener listener) {monitemclicked = Liste
  Ner @Override public void Setonitemlongclicklistener (Adapterview.onitemlongclicklistener listener) {Monitem
  longclicked = listener; Private Datasetobserver Mdataobserver = new Datasetobserver () {@Override public void onchanged () {sy
      Nchronized (horizontallistview.this) {mdatachanged = true;
      } invalidate ();
    Requestlayout ();
      @Override public void oninvalidated () {reset ();
      Invalidate ();
    Requestlayout ();

  }

  };
  @Override public ListAdapter Getadapter () {return madapter;
}
  @Override public View Getselectedview () {//todo:implement return null; @Override public void Setadapter (ListAdapter adapter) {if (Madapter!= null) {Madapter.unregisterdatase
    Tobserver (Mdataobserver);
    } Madapter = adapter;
    Madapter.registerdatasetobserver (Mdataobserver);
  Reset ();
    Private synchronized void Reset () {Initview ();
    Removeallviewsinlayout ();
  Requestlayout (); @Override public void setselection (int position) {//todo:implement} private void Addandmeasurechild (fi
    NAL View Child, int viewpos) {Layoutparams params = Child.getlayoutparams ();
    if (params = = null) {params = new Layoutparams (layoutparams.fill_parent, layoutparams.fill_parent);
    } addviewinlayout (Child, Viewpos, params, true); Child.measure (Measurespec.makemeasurespec (GetWidth (), Measurespec.at_most), Measurespec.makemeasurespec (g
  Etheight (), measurespec.at_most)); } @OveRride protected synchronized void OnLayout (Boolean changed, int left, int. top, int right, int bottom) {super.

    OnLayout (changed, left, top, right, bottom);
    if (Madapter = = null) {return;
      } if (mdatachanged) {int oldcurrentx = Mcurrentx;
      Initview ();
      Removeallviewsinlayout ();
      MNEXTX = Oldcurrentx;
    Mdatachanged = false;
      } if (Mscroller.computescrolloffset ()) {int scrollx = Mscroller.getcurrx ();
    MNEXTX = SCROLLX;
      } if (mnextx <= 0) {mnextx = 0;
    Mscroller.forcefinished (TRUE);
      } if (Mnextx >= mmaxx) {mnextx = Mmaxx;
    Mscroller.forcefinished (TRUE);

    int dx = MCURRENTX-MNEXTX;
    Removenonvisibleitems (DX);
    Filllist (DX);

    Positionitems (DX);

    Mcurrentx = MNEXTX; if (!mscroller.isfinished ()) {post (new Runnable () {@Override public void run () {request
        Layout ();

    }
      }); } Private VOID filllist (final int dx) {int edge = 0;
    View child = Getchildat (Getchildcount ()-1);
    if (child!= null) {edge = Child.getright ();

    } filllistright (Edge, DX);
    Edge = 0;
    Child = Getchildat (0);
    if (child!= null) {edge = Child.getleft ();

  } filllistleft (Edge, DX); private void Filllistright (int rightedge, final int dx) {while (Rightedge + dx < getwidth () &&amp ; Mrightviewindex < Madapter.getcount ()) {View child = Madapter.getview (Mrightviewindex, Mremovedviewqu
      Eue.poll (), this);
      Addandmeasurechild (Child,-1);

      Rightedge + + child.getmeasuredwidth ();
      if (Mrightviewindex = = Madapter.getcount ()-1) {Mmaxx = Mcurrentx + rightedge-getwidth ();
      } if (Mmaxx < 0) {Mmaxx = 0;
    } mrightviewindex++; } private void Filllistleft (int leftedge, final int dx) {while (Leftedge + dx > 0 && Mleftviewinde X >= 0) {View child = Madapter.getview (Mleftviewindex, Mremovedviewqueue.poll (), this);
      Addandmeasurechild (child, 0);
      Leftedge-= Child.getmeasuredwidth ();
      mleftviewindex--;
    Mdisplayoffset-= Child.getmeasuredwidth ();
    }} private void Removenonvisibleitems (final int dx) {View child = getchildat (0);
      while (child!= null && child.getright () + dx <= 0) {Mdisplayoffset = = Child.getmeasuredwidth ();
      Mremovedviewqueue.offer (child);
      Removeviewinlayout (child);
      mleftviewindex++;

    Child = Getchildat (0);
    Child = Getchildat (Getchildcount ()-1);
      while (child!= null && child.getleft () + dx >= getwidth ()) {mremovedviewqueue.offer (child);
      Removeviewinlayout (child);
      mrightviewindex--;
    Child = Getchildat (Getchildcount ()-1);
      } private void Positionitems (final int dx) {if (Getchildcount () > 0) {mdisplayoffset = dx; int left = mDisplayoffset;
        for (int i = 0; i < Getchildcount (); i++) {View child = Getchildat (i);
        int childwidth = Child.getmeasuredwidth ();
        Child.layout (left, 0, left + childwidth, child.getmeasuredheight ());
      Left + + Childwidth + child.getpaddingright ();
    }} public synchronized void Scrollto (int x) {mscroller.startscroll (mnextx, 0, X-MNEXTX, 0);
  Requestlayout ();
    @Override public boolean dispatchtouchevent (Motionevent ev) {Boolean handled = super.dispatchtouchevent (EV);
    Handled |= mgesture.ontouchevent (EV);
  return handled; Protected Boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float velocityy) {synchronized
    (horizontallistview.this) {mscroller.fling (MNEXTX, 0, (int)-velocityx, 0, 0, mmaxx, 0, 0);

    } requestlayout ();
  return true;
    } protected Boolean Ondown (Motionevent e) {mscroller.forcefinished (true);
  return true; } private Ongesturelistener mongesture = new Gesturedetector.simpleongesturelistener () {@Override public boolean Ondo
    WN (Motionevent e) {return HorizontalListView.this.onDown (e);
      @Override public boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float velocityy) {
    Return horizontallistview.this. Onfling (E1, E2, Velocityx, Velocityy);

      @Override public boolean onscroll (Motionevent E1, motionevent E2, float Distancex, float distancey) {
      Synchronized (horizontallistview.this) {mnextx + = (int) Distancex;

      } requestlayout ();
    return true; @Override public boolean onsingletapconfirmed (Motionevent e) {for (int i = 0; i < Getchildcount (); i+
        +) {View child = Getchildat (i); if (Iseventwithinview (e, child)) {if (monitemclicked!= null) {Monitemclicked.onitemclick (Horizont Allistview.this, Child, MLe.Ftviewindex + 1 + i, Madapter.getitemid (mleftviewindex + 1 + i));
                } if (monitemselected!= null) {monitemselected.onitemselected (Horizontallistview.this,
          Child, Mleftviewindex + 1 + i, Madapter.getitemid (mleftviewindex + 1 + i));
        } break;
    } return true;
      @Override public void onlongpress (Motionevent e) {int childcount = Getchildcount ();
        for (int i = 0; i < ChildCount. i++) {View child = Getchildat (i); if (Iseventwithinview (e, child)) {if (monitemlongclicked!= null) {MONITEMLONGCLICKED.ONITEMLONGCL Ick (Horizontallistview.this, Child, Mleftviewindex + 1 + i, madapter.
          Getitemid (Mleftviewindex + 1 + i));
        } break; }} Private Boolean Iseventwithinview (Motionevent E, View child) {Rect Viewrect = nEW Rect ();
      int[] childposition = new int[2];
      Child.getlocationonscreen (childposition);
      int left = childposition[0];
      int right = left + child.getwidth ();
      int top = childposition[1];
      int bottom = top + child.getheight ();
      Viewrect.set (left, top, right, bottom);
    return Viewrect.contains ((int) e.getrawx (), (int) E.getrawy ());

}
  };

 }

Adapter Horizontallistviewadapter. Java is as follows:

public class Horizontallistviewadapter extends Baseadapter {/** contexts/private context mcontext;

  /** image Data Source * * Private arraylist<map<string, integer>> mimagelist;
  /** Data Source * * Private arraylist<map<string, integer>> mtextlist;

  /** image */private static String Image = "Ic_";

  Private map<string, integer> mMap = null;
    /** Construction Method/Public Horizontallistviewadapter {this.mcontext = context;
  InitData ();
    /** Initialization Data */public void InitData () {mimagelist = new arraylist<map<string, integer>> ();
    * * * Reflective technology * * class<?> imageclzz = R.drawable.class;
    r.drawable instance = new R.drawable ();
    Gets all the fields in the Drawable class field[] fields = Imageclzz.getdeclaredfields ();
      for (field Field:fields) {//Get the name of the field, String name = Field.getname (); if (name!= null && name.startswith (IMAGE)) {try {mMap = new hashmap<string, IntegEr> ();
          Mmap.put (IMAGE, (Integer) Field.get (instance));
        Mimagelist.add (MMAP);
        catch (Illegalaccessexception e) {e.printstacktrace ();
  @Override public int GetCount ()}} {return mimagelist.size (); @Override public map<string, integer> getitem (int position) {return mimagelist = null? null:mimagel
  Ist.get (position);
  @Override public long getitemid (int position) {return position;
    @Override public View getview (int position, View Convertview, ViewGroup parent) {Viewholder holder;
      if (Convertview = = null) {holder = new Viewholder ();
      Convertview = Layoutinflater.from (Mcontext). Inflate (R.layout.horizontal_list_item, NULL);
      Holder.mimage = (ImageView) convertview. Findviewbyid (R.id.iv_list_item);
      Holder.mtitle = (TextView) convertview. Findviewbyid (R.id.tv_list_item);
    Convertview.settag (holder); } else {holder = (Viewholder) convertview.gettag ();
    } if (position = = Mselectindex) {convertview.setselected (true);
    else {convertview.setselected (false);
    } holder.mImage.setImageResource (GetItem (position). Get (IMAGE);
  return convertview;
  Private class Viewholder {/** image * * Private imageview mimage;
 }
}

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.