ListView Example of horizontal sliding (horizontal sliding) in Android

Source: Internet
Author: User
Tags final integer null null reset

This article mainly introduces the android to achieve horizontal sliding (transverse sliding) ListView example, this article with its own encapsulation of a control method to solve this requirement, the need for friends can refer to the

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:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30-31 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 The 96 97 98 99 100 101 102 103 104 105 106 107 108 109 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140-1 41 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170-171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201-2 02 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231-232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262-2 63 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298-299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329-3 30 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359-360 361 /** * Horizontal 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 ();}   Privat e 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) { monitemselected = listener; }   @Override public void Setonitemclicklistener (Adapterview.onitemclicklistener listener) {monitemclicked = Listener }   @Override public void Setonitemlongclicklistener (Adapterview.onitemlongclicklistener listener) { monitemlongclicked = listener; }   Private Datasetobserver mdataobserver = new Datasetobserver () {  @Override public void onchanged () {SYNCHR Onized (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.unregisterdatasetobserver (mdataobserver);} Madapter = adapter; Madapter.registerdatasetobserver (Mdataobserver); Reset (); }   Private synchronized void reset () {Initview (); Removeallviewsinlayout (); Requestlayout ();}   @Override Pub LIC void setselection (int position) {//todo:implement}   private void Addandmeasurechild (final View child, int VI Ewpos) {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 ( GetHeight (), 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 () {requestlayout ();}});  } }   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 () && Mrightviewindex < Madapter.getcount ()) {  View child = Madapter.getview (Mrightviewindex, Mremove Dviewqueue.poll (), this); Addandmeasurechild (Child,-1); Rightedge + + child.getmeasuredwidth ();   if (Mrightviewindex = Madapter.getcount ()-1) {Mmaxx = Mcurrentx + Rightedge-getwidth ();}   if (Mmaxx &L T 0) {Mmaxx = 0;} mrightviewindex++; }  }   private void filllistleft (int leftedge, final int dx) {while (Leftedge + dx > 0 && Mleftview Index >= 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); removeviewinlayou T (child); mrightviewindex--; Child = Getchildat (Getchildcount ()-1); }   private void Positionitems (final int dx) {if (Getchildcount () > 0) {mdisplayoffset = dx; int left = Mdisp Layoffset; for (int i = 0; i < Getchildcount (); i++) {View child = Getchildat (i); int childwidth = Child.getmeasuredwidth (); chil D.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); Han dled |= mgesture.ontouchevent (EV); return handled; }   Protected Boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float velocityy) {synchronized (horizontallistview.this) {mscroller.fling (MNEXTX, 0, (int)-velocity X, 0, 0, mmaxx, 0, 0); } requestlayout ();   return true; }   Protected Boolean ondown (Motionevent e) {mscroller.forcefinished (true); return true;}   Private Ongesturel Istener mongesture = new Gesturedetector.simpleongesturelistener () {  @Override public boolean ondown (Motionevent E {return HorizontalListView.this.onDown (e);}   @Override public boolean onfling (Motionevent E1, motionevent E2, FL Oat Velocityx, float velocityy) {return horizontallistview.this. Onfling (E1, E2, Velocityx, Velocityy);}   @Overrid E public boolean onscroll (Motionevent E1, motionevent E2, float Distancex, float distancey) {  synchronized (Horizon Tallistview.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 (Horizontallistview.this, Child, Mleftviewindex + 1 + i, Madapter.getitemid (mleftviewindex + 1 + i)); } if (monitemselected!= null) {monitemselected.onitemselected (horizontallistview.this, Child, Mleftviewindex + 1 + i, MA Dapter.getitemid (Mleftviewindex + 1 + i)); } break; }   return true; }   @Override public void onlongpress (Motionevent e) {int childcount = Getchildcount (), for (int i = 0; i < child Count; i++) {View child = Getchildat (i); if (Iseventwithinview (e, child)) {if (monitemlongclicked!= null) {monitemlongclicked . Onitemlongclick (Horizontallistview.this, Child, Mleftviewindex + 1 + i, Madapter.getitemid (mleftviewindex + 1 + i)); } break; }}   Private Boolean Iseventwithinview (Motionevent E, View child) {Rect viewrect = new Rect (); int[] Childpositio n = 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:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5 86 87 88 89 90 91 92 93 public class Horizontallistviewadapter extends Baseadapter {/** contexts/private context mcontext;/** image Data Source * * Private Ar Raylist<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>> ();/* * Reflection Technology/CLASS<?&G T 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<stri Ng, integer> getitem (int position) {  return mimagelist = = null null:mImageList.get (position);}   @Over Ride public long getitemid (int position) {return position.}   @Override public view GetView (int position, View conv Ertview, 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.