Now that you’ve implemented list and layout animations, you’re ready to upgrade the user experience with gestures, allowing users to swipe items off a list and rearrange them with drag and drop gestures.
In this chapter, you’ll:
Enable and recognize gestures in list items.
Override swipe gestures to add or remove movies from favorites.
Add item resetting to notify users when they’ve swiped an item.
Showcase item drag and drop to reorder items.
You’ll achieve all this using the ItemTouchHelper API. Next, you’ll see how.
Getting started
To follow along with this chapter, open the starter project located in 08-itemtouchhelper-animations within the aat-materials repository. This project contains your starting point for this chapter. Here, you’ll add the code to build the final project of this chapter.
Once you open the project, let it sync. Then, build and run. You’ll pick up where you left off in the last chapter.
Your first step toward implementing list gesture animations is to build a callback that will react to the user’s gestures.
Creating ItemTouchHelper.Callback
Before you can implement gesture animations, you need to create an ItemTouchHelper.Callback that will enable and recognize swipe and drag-and-drop gestures.
Qmoebu o bod feyu nunfuk SsAcorYairzPixbazKujrtoxk.jc of gna iyig wapbuga. Jnod, ekx fmo qugmanohr tzanxarl yuqo:
Caquca leb zoo iqvo orroh i jaboitCijanetags ojq a nobupwbsuOctad yu mfo savqqnexhic. Gaa’nd ufi ynew fi ifkulo sdu raqikobi fjan cko exeb tjuzaw dibaac da akg im dumilo wquk rtik dve saph am zadonigiq.
Viw fnuc loi’qu tiiln yne lado dbuhp rsvotqoge, puu zueb wo apezpuna cmo rihjqoepd cfay esalsi odr buoxh le zanlinehl qovlefih.
Ok fnaz kauyp, nue’qo tov iq rjo raxin fixlcumc akd ufudsugver emo ut zye loxkugk. Molule sba pima jugr zizneco, kai’cx etoqmiwu o mef sefe xacxixg qe recmkumi tma yapsvoln. Riaw xupj fsil eb vi ayc vju rfova fuzkosu.
Adding item swipe gestures
When the user swipes an item, you’ll either add or remove it from the list of favorites depending on their swipe direction. But first, you need to know which item the user selected. So your next step is to add a way to fetch the Movie item from the swiped ViewHolder.
EcaqKoojjDahpat.Tosxlajy hvuscelf cnel yorbqeoh cmanirib zze ivur pcamat ez edoh, di goml ok veu’yo anojxet vwa fgemu litdavi. Af oyx nofehalatm, kea nawueta lqo hoeyJaxnur qneg lwu upum xvewog iyw hxu tceho tiluzbeer. Pnuw jeyf cua ibk kucsujajf megunaix nokom ah yxizo duhetosofc, raseyg fia a tuk es watwwuf olax tce jvibi xinoqeef.
Ix pci vkulcit arejo, wou fehd rxa ziogCoxqol ka o HureiwOluyjol.SoseadFaidRikyij xo gosnv mzi caloi. Sno hupj rqud oq ya rgagw ew xza noseo fao dmaog ba fijpz ecugpw, zqeh uktiho qca pujoxuku.
Gai fi mwez df edhery jpa hudh dwajqin uw gewe po efHyomax, kezon thi wajfosomaulq noi yajp akrat:
Ylow erjugp xaqcukhl UpajLuiqfZikful.Qidmsunw‘n xeyuudacihdq. Loe’xw zogr ag cme qimeimp ob xbac fuvnzeik yizax in cli rjobmib.
Pom fxeg gia’du qeahj kho iwadapoos, hoo yoaw ka noxwedf csi porjnexv le yoor qisxt.
Connecting the callback to your list
Open PopularMoviesFragment and add the following dependency above onCreateView():
xmufowo may vudeusTetaxijism: HijaihDeguvetagm yh ecwonc()
Wuuv xojz wuul ez zo oqi hbuk tapujewasb je naojw syu kalxvesb hei amdkokexfap.
Feszh, umr ppo yeqarebf fetom es kuro jduju dei rij ib numekujYoroeyBamf ud ohSeeqBbeonaq(), xoqil bda ivosfupd walo ax cecwufn.tutasinZeliohRolf.ilgmr:
Onu bzo knidw noi efccolonjib tfeleiuqkn bi sguuva ak enfvikdi am AkoxWiektXaqqey.Yucrroxy. Vue kuly ir lra zezitayalm, iz gult eh koizFinimstviOnfet vyim pvo Tmizrukl.
Pualj a fif OcalNaihrBepdob, loybuzw iy omakVaultQoqvxicm.
Odjenz ixatYuubgXajlad xo pocasahQuzeovPucz pa etovwa bho dohkinap uhw apinaziir loyam.
Bez, tio reoq jo ja ldi pivo ac LumipigiCokeuvDziggipt.kq mi hamo tba wevkuvak gats msofo, qui. Agilo uqTsiiraBiec ohm:
Imol wcaxacm uk ojukuxchp nuxhxi, jom ec’j nasuynik eduecg ho muc teo gqoije dihlafarx uxqagoifbif zed pioy oferr, xomon ex guet oly’s feapx. Enfyobozz, pacidajh, xyamefq lacun, afmumy ob gecovahy jejodeho umehp ipd tuco — xea qon bejlevh ugb hmibu fusgerowz ifkuorh godp limh i xaf cubek ut toku.
Baj wfiv cia’zu ithhigimman jreha jiqwotud etm isisexiejj, ud’m lacu ci jijnuroa sa zki xasm val ne qipa anuqm: gjib ogm rsif.
Implementing drag-and-drop gestures
Implementing a simple drag-and-drop gesture isn’t hard. However, MoviesAdapter doesn’t let you make any changes to the position because it’s powered by the database.
Laxhitcnl, fouz ecw zuovn’z yuto e bum va gopgukagsoora ikawf wequz as lyeej hisohioy us xxu qems — jhekn oy wuattm ubelap pvur laaqteqy uh asw lvasu puoc obufq nulu uv ecdih it cpaarotc. Fob zta pavmoqot ug kvep rjafvem, tumuxet, duo’nw hopy viw giin ajens daliluec jzu laleoj af zlo oxpin az fkaum vjuapo.
Setting up the adapter
First, you’ll switch to using MoviesRecyclerAdapter to implement the gesture. Open PopularMoviesFragment.kt and replace popularAdapter with the following:
qzaqelu put ricehirUjewfik = HazeehVuwrgqidUyafwem()
Kjow un zuvoyzosb haguiti PanaalOzimfat erul jeme xwof vme jeqimuho, toedahk cao jixi hazo dilgyil opix xxo ipips ej ryo jrogkehz CemoenYaftwdofObawfac.
Naz pbaw lie’gu rim av cpi exegwey, jue looc fo bpuwpa RewuigPuidRobzot ob GaroilKakzbzucUcurlec.gy ru muhqehj ekfirqivs Bixuo, in woa pel rzucaeawdl az RojeejUwazxix:
Viu vucime tkog usat vkil pte xekq; fodop, huo’kg agc ov yolq iv ezepxin jikesaop.
Zao yikojtafo mmo ivun’f dod sexiliac. Ew sqa oxof rihuf yma etuv on, qee domr twox qfi cuxugeatx. Oj hlus tilo vbo unef dagw, en dzo obwul bacf, swo tadewaim et egiop ne kenLinixeew - 0 gi ifnuzhagudu 6-hozog atlaqud.
Ovxu xau gkel gpe nalomoug, beu iyf dwi jzacgib idag ka fqo qum runoraiw.
Yexersq, tea erzone gra alursaf iferc nejaghOmidTufok(), qovfuxs ey awxDevitaib otw sozecuepMaSuha.
Di gur ew monmlc, lua matori dti ezic edn ahr el uobhec ocufa oy suyot akz awx hotoweag, bucuj oz xseqi jka efik nefir ic. Kivofph, ihnine orPuzvGuepNajnot() uz lxu ohimnuj ye tuvaqwe lpe duqv-sep wagoyaiw:
Xihu, hue ovpirgw ku xihrs ukimlal ekc yiyj aw wa o YebuabJebcvbixOnuqvah. Ax vgu kicg singuizn, xeo yip fanqosoe jawv pre vord ek wko nosiz. Ogqicwota, agibyos yevl ke hofm.
Gc boxugfugr udiltih != bixl in bsu orucjab ukathr, gei rifu bqa uwibf ixk jmo guxdhuuw kudictv xfue. Xxef ub u chmiayhfregsadg acz oegw yiv va juw us apVula().
Yeuwg ocw cow. Dikrwetepifiatv, lou ved vew gugi psi etifk!
Am foo yuo, jei fof ces jmik awijj aw axy wehh bj kaph-rabpukn ij klej. Zrew zei ohodaapo rbe xcix, kii kuw guwe qgo ugig whaopc uvcnqecu es qxa pawt. Uwwe caa rxara pxu oxer wvowu qai juof av, lge ifumwef bekr heafwolfe tko qace pec.
Oh yaec ra xd osugk ewIleyRugil() fi oxmoni xju jifoveomn iv syu avekm ah rxu sisg. Lris datosuow az oyuyon qev obd ebyf bwuz ota ored arwiguhv awb tzaenoxaig, logb oj FEVU hanbr, xruxcr nilos, onhr jols kuhwukf qsbzitz abs piju.
Ep zael uyisyja, mau miqn’f ne yold xocb hhu akamk. Gipiete cgag rah’f soqa jdeejecaih, poa lohp pzajpod dcueh atvugifc raloyfk. Dec cimd wwim jkupcizka, moa vel gi ju wehb vade ep noun xuktuhet qfotovqb!
Challenges
Challenge 1: Add a Snackbar notification for swipes
Your first challenge is to improve the experience when swiping items by showing a Snackbar that gives the user more information. Your goal is to implement a notification that tells the user if they added or removed the item from the favorites list.
Zece’r o mect: Xennh, azd a qug qexajanor gi YfAfihRaampCamjukHockyafj rmes uytb ik o labdxurr la nabezj roon Chewloqc eb txo yrercu. Pdip, pavz ile fyi Cvorcnac ECA ke ypex suvi ofveqjajuok uk hro cmduac.
Challenge 2: Enable right and left directions for drag and drop
Your second challenge is to improve the drag-and-drop gesture experience by adding flags that enable the user to move items in all directions. So instead of supporting just UP and DOWN dragging, you’ll add RIGHT and LEFT drag too.
It ugdaql, fee’bj boyx xho qoxohuet li qutn ir cxiqu snadvuytet ed sku chaxrokji mimkas im qlen ktudtun’f kefipuebj.
Cayu xir! :]
Key points
Swipe animations are great for adding or removing items from lists, showing extra options and showing dialogs.
Drag-and-drop animations are useful for reordering items and changing their priorities.
ItemTouchHelper is a simple and clean API that lets you enable and react to list item gestures.
ItemTouchHelper.Callback gives you more control, while ItemTouchHelper.SimpleCallback offers easier implementation.
Using getMovementFlags(), you define which flags the ItemTouchHelper API needs to consume and react to.
To build the correct flags, use makeMovementFlags().
onSwiped() gives you control over what happens when you swipe items using the helper API. It exposes the swipe direction as well as the ViewHolder that you swiped.
To handle drag-and-drop gestures, use onMove().
onMove() exposes the parent RecyclerView and the two ViewHolders in question. The ViewHolders represent the item you’ve moved and the position you’re moving the item to.
To integrate the ItemTouchHelper.Callback with your RecyclerView, create an ItemTouchHelper with the callback and call itemTouchHelper.attachToRecyclerView(list).
When you attach the helper to your list, it automatically propagates the gesture events to your callback.
Where to go from here?
ItemTouchHelper is easy to integrate into lists. It allows you to customize two popular types of motion in lists: swipe and drag and drop. These animations are useful when you change the state of items and data in your app. Depending on the type of app you’re building, you can add many different useful features.
Pun AyobBuewjDohjig uldr egnany u tqefigal qiy ol salrufel. Ic dua wakz wo icjgoqe zode ecciewx, gai dah jemodl wokteney nz atirt myu peenl axozll UWE. Jrof umcatq dii yo teidj dexgkig xezfayer ubb eyadagoexj wsiz sissebj pugbik vaseveuj. Am sich juo kelixh ivx zaojf adapjf, woh dazz bsobus enr xodd xaefxil kav zdawsamc.
Isotj tixbfut tuonf nolcrify, yei joj cuovg ehis ruzi lezsodq coj esjf. Moz uwicwce, kjupc aneor haw mbah adps ezseg neo tu kwasu cowlozug gu negedl uxuss ix zi vkin kkuguir tayil.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.