Draggable Symbols I
Draggable Symbols I
Draggable Symbols I
Draggable Symbols I
For many possible applications in design, modeling, games, and so on, it is important for the user to be able to drag symbols from one part of the display screen to another. For example, in touchscreen Android phones it is common to move application icons to different positions or different folders by long-pressing (holding down longer than a tap) on the icon with a finger, dragging it to the new location, and then raising your finger. In this project we develop some techniques for dragging arbitrary user-defined symbols around the screen.
as its parameters.
Copying Resources
Let's go ahead and copy some resources that we will use. Open the course images directory and copy the files green_square.png, red_square.png, and yellow_square.png to the res/drawable-hdpi directory of the DraggableSymbols project.
11/06/2012
Draggable Symbols I
ipr adodve.oinvn; mot nri.iwMtoEet ipr adodve.iw mot nri.iwVe; / * Dmntaino oewyt ptasto dagbesmoso sre. eosrto f n a o u e f rgal ybl n cen Aatdloeyfo mtra dsusdi dpe osl rm aeil icse n ht:/nri-eeoesboso.o/000/aigsneo-uttuhhm tp/adoddvlpr.lgptcm21/6mkn-es-fmlioc.tl Seas e lo ht:/nri-eeoesboso.o/000/o-ohv-orcpaeadeti-o.tl tp/adoddvlpr.lgptcm21/7hwt-aeyu-uck-n-a-ttohm Ti eaperqie ol AI3(nri 15. hs xml eurs ny P Adod .) * /
pbi casSmoDagretnsVe { ulc ls yblrge xed iw / Clr frbcgon adtx / oos o akrud n et sai fnlitBCGON_OO =Clrag(5,0 0 0; ttc ia n AKRUDCLR oo.rb25 , , ) sai fnlitHAE_OO =Clrag(5,3,3,3) ttc ia n EDRCLR oo.rb25 0 0 0; sai fnlitTX_OO =Clrag(5,5,5,) ttc ia n ETCLR oo.rb2525250; piaeitnmeSmos rvt n ubrybl; piaeDaal [ smo; rvt rwbe ] ybl piaeit[ smoIdx rvt n ] yblne; piaefot[ X rvt la ] ; piaefot[ Y rvt la ] ; piaeit[ smoWdh rvt n ] yblit; piaeit[ smoHih; rvt n ] yblegt piaefot[ lsTuh; rvt la ] atocX piaefot[ lsTuh; rvt la ] atocY piaeitsmoSlce; rvt n ybleetd piaePitpit rvt an an; / Ttlnme o smost ue / oa ubr f ybl o s / Aryo smos(ieso nmeSmos / ra f ybl dmnin ubrybl) / Idxo daal rsuc (.rwbesmo) / ne f rwbe eore Rdaal.ybl / Cretxcodnt,uprlf cre o smo i / urn oriae pe et onr f ybl / Cretycodnt,uprlf cre o smo i / urn oriae pe et onr f ybl / Wdho smo i / it f ybl / Hih o smo i / egt f ybl / xcodnt o smo ia ls tuh / oriae f ybl t at oc / ycodnt o smo ia ls tuh / oriae f ybl t at oc / Idxo smo ls tuhd(1i nn slce) / ne f ybl at oce - f oe eetd
/ Floigdfn uprlf adlwrrgtcreso dslysaercage / olwn eie pe et n oe ih onr f ipa tg etnl piaeitsae1=0 rvt n tgX ; piaeitsae1=4; rvt n tgY 5 piaeitsae2=50 rvt n tgX 0; piaeitsae2=50 rvt n tgY 0; piaeboeniDagn =fle rvt ola srgig as; / Tu i sm smo i cretybigdagd / re f oe ybl s urnl en rge
pbi SmoDagrCnetcnet fot],fot],it]yblne){ ulc yblrge(otx otx, la[X la[Y n[smoIdx / Cl truht smls cntutro Ve sprls / al hog o ipet osrco f iw uecas sprcnet; ue(otx) / Stu lclary dfnn smosadterpstos / e p oa ras eiig ybl n hi oiin ti. =X hsX ; ti. =Y hsY ; ti.yblne =smoIdx hssmoIdx yblne; nmeSmos=Xlnt; ubrybl .egh smo =nwDaal[ubrybl] ybl e rwbenmeSmos; smoWdh=nwitnmeSmos; yblit e n[ubrybl] smoHih =nwitnmeSmos; yblegt e n[ubrybl] lsTuh =nwfotnmeSmos; atocX e la[ubrybl] lsTuh =nwfotnmeSmos; atocY e la[ubrybl]
/ Fl tesmo ary wt dt / il h ybl ras ih aa friti0 inmeSmos i+{ o(n =; <ubrybl; +) smo[]=cnetgteore(.eDaal(yblne[]; ybli otx.eRsucs)gtrwbesmoIdxi) smoWdhi =smo[]gtnrniWdh) yblit[] ybli.eItiscit(; smoHih[]=smo[]gtnrniHih(; yblegti ybli.eItiscegt) smo[]stons00smoWdhi,yblegti) ybli.eBud(,,yblit[]smoHih[]; }
eagle.phys.utk.edu/guidry/android/DraggableSymbols.html 2/9
11/06/2012
Draggable Symbols I
/ Stu tePitojc ta wl cnrlfra o sre das / e p h an bet ht il oto omt f cen rw pit=nwPit) an e an(; pitstnila(re; an.eAtAistu) pitstetie1) an.eTxSz(4; pitsttoeit() an.eSrkWdh0; }
/ PoesMtoEet crepnigt sre tuhsaddas MtoEet * rcs oinvns orsodn o cen oce n rg. oinvn rprsmvmn (os,pn fne,takal eet.TeMtoEetmto eot oeet mue e, igr rcbl) vns h oinvn ehd gtcin)rtrstekn o ato bigpromda a itgrcntn o eAto( eun h id f cin en efre s n nee osat f teMtoEetcas wt psil vle ATO_ON ATO_OE ATO_P h oinvn ls, ih osbe aus CINDW, CINMV, CINU, adATO_ACL Tu w cnsic o tertre itgrt dtriete n CINCNE. hs e a wth n h eund nee o eemn h kn o eetadteaporaeato. id f vn n h prpit cin * / @vrie Oerd pbi boenoTuhvn(oinvn e){ ulc ola nocEetMtoEet v fnlitato =e.eAto(; ia n cin vgtcin) sic (cin { wth ato) / MtoEetcascntn sgiyn afne-oneet / oinvn ls osat infig igrdw vn cs MtoEetATO_ON { ae oinvn.CINDW: iDagn =fle srgig as; / Gtcodntso tuheet / e oriae f oc vn fnlfotx=e.eX) ia la vgt(; fnlfoty=e.eY) ia la vgt(; / Iiilz / ntaie smoSlce =-; / - i tuhntwti cretbud o sm smo ybleetd 1 / 1 f oc o ihn urn ons f oe ybl / Dtriei tuhwti bud o oeo tesmos / eemn f oc ihn ons f n f h ybl friti0 inmeSmos i+{ o(n =; <ubrybl; +) i(xXi & x([]smoWdhi) & (>[] f(>[] & <Xi+yblit[]) & yYi & y([]smoHih[]) { & <Yi+yblegti)) smoSlce =i ybleetd ; bek ra; } } / I tuhwti bud o asmo,rmme satpsto frti smo / f oc ihn ons f ybl eebr tr oiin o hs ybl i(ybleetd>-) fsmoSlce 1{ lsTuh[ybleetd =x atocXsmoSlce] ; lsTuh[ybleetd =y atocYsmoSlce] ; } bek ra; } / MtoEetcascntn sgiyn afne-rgeet / oinvn ls osat infig igrda vn cs MtoEetATO_OE { ae oinvn.CINMV: / Ol poesi tuhslce asmo / ny rcs f oc eetd ybl i(ybleetd>- ) fsmoSlce 1 { iDagn =tu; srgig re
eagle.phys.utk.edu/guidry/android/DraggableSymbols.html 3/9
11/06/2012
Draggable Symbols I
fnlfotx=e.eX) ia la vgt(; fnlfoty=e.eY) ia la vgt(; / Cluaetedsac mvd / aclt h itne oe fnlfotd =x-lsTuh[ybleetd; ia la x atocXsmoSlce] fnlfotd =y-lsTuh[ybleetd; ia la y atocYsmoSlce] / Mv teojc slce / oe h bet eetd XsmoSlce]+ d; [ybleetd = x YsmoSlce]+ d; [ybleetd = y / Rmme ti tuhpsto frtenx mv eeto ti ojc / eebr hs oc oiin o h et oe vn f hs bet lsTuh[ybleetd =x atocXsmoSlce] ; lsTuh[ybleetd =y atocYsmoSlce] ; / Rqetarda / eus erw ivldt(; naiae) } bek ra; } / MtoEetcascntn sgiyn afne-peet / oinvn ls osat infig igru vn cs MtoEetATO_P ae oinvn.CINU: iDagn =fle srgig as; ivldt(; / Rqetrda naiae) / eus erw bek ra; } rtr tu; eun re }
/ Ti mto wl b cle ec tm tesre i rdan Teda i / hs ehd il e ald ah ie h cen s erw. h rw s / o teCna ojc,wt fratn cnrle b tePitojc. / n h avs bet ih omtig otold y h an bet / We t rda i udrAdodcnrl btw cnrqetarda / hn o erw s ne nri oto, u e a eus erw / uigtemto ivldt( ihrtdfo teVe sprls. / sn h ehd naiae) neie rm h iw uecas @vrie Oerd pbi vi oDa(avscna){ ulc od nrwCna avs sproDa(avs; ue.nrwcna) / Da bcgons / rw akrud daBcgon(an,avs; rwakrudpitcna) / Da aldagbesmosa tercretlctos / rw l rgal ybl t hi urn oain friti0 inmeSmos i+{ o(n =; <ubrybl; +) cna.ae) avssv(; cna.rnlt([]Yi) avstasaeXi,[]; smo[]da(avs; ybli.rwcna) cna.etr(; avsrsoe) } iDagn =fle srgig as; }
/ Mto t da tebcgon frtesre. Ivkdfo oDa ec tm / ehd o rw h akrud o h cen noe rm nrw ah ie / tesre i rdan / h cen s erw. piaevi daBcgon(an pit Cna cna) rvt od rwakrudPit an, avs avs{ / Da hae brbcgon / rw edr a akrud pitstoo(EDRCLR; an.eClrHAE_OO) cna.rwet00sae2sae2pit; avsdaRc(,,tgX,tgY,an)
eagle.phys.utk.edu/guidry/android/DraggableSymbols.html
4/9
11/06/2012
Draggable Symbols I
/ Da mi saebcgon / rw an tg akrud pitstoo(AKRUDCLR; an.eClrBCGON_OO) cna.rwetsae1sae1sae2sae2pit; avsdaRc(tgX,tgY,tgX,tgY,an) / I dagn asmo,dslyisxadycodntsi araot / f rgig ybl ipa t n oriae n edu i(srgig{ fiDagn) pitstoo(ETCLR; an.eClrTX_OO) cna.rwet" ="XsmoSlce] 20 1,pit; avsdaTx(X +[ybleetd, 0, 8 an) cna.rwet" ="YsmoSlce] 20 3,pit; avsdaTx(Y +[ybleetd, 0, 3 an) } } }
/ TeDaal crepnigt tesmo.Rdaal.ierfr t fl.n,.p, / h rwbe orsodn o h ybl .rwbefl ees o iepg jg / o .i soe i rsdaal-di(eeecdfo cd wtotteetnin. / r gf trd n e/rwbehp rfrne rm oe ihu h xeso) it]yblne ={.rwberdsur,Rdaal.re_qae Rdaal.elwsur} n[smoIdx Rdaal.e_qae .rwbegensur, .rwbeylo_qae; / IsataeaSmoDagrisac (hc sblse Ve) psigt i i te / ntnit yblrge ntne wih ucass iw, asn o t n h / cntutrtecnet(hs adteaoeary. Te sttecnetve t / osrco h otx ti) n h bv ras hn e h otn iw o / ti isac o SmoDagr(otelyu i bigseiidetrl b SmoDagr / hs ntne f yblrge s h aot s en pcfe niey y yblrge, / wt n XLlyu fl) Tersligve sol te paedagbesmoswt / ih o M aot ie. h eutn iw hud hn lc rgal ybl ih / iiilcnetadpsto dfndb teaoeary o tesre. / nta otn n oiin eie y h bv ras n h cen SmoDagrve =nwSmoDagrti,X Y smoIdx; yblrge iw e yblrge(hs , , yblne) ve.eLyuPrm(e VeGopLyuPrm(iwru.aotaasFL_AET iwstaotaasnw iwru.aotaasVeGopLyuPrm.ILPRN, VeGopLyuPrm.ILPRN); iwru.aotaasFL_AET) stotnVe(iw; eCnetiwve) } }
eagle.phys.utk.edu/guidry/android/DraggableSymbols.html 5/9
11/06/2012
Draggable Symbols I
It isn't essential, but to emphasize that our layout has been created entirely in Java, you can go to the res/layout directory of the project and delete the main.xml file, since we are not using it. This file was produced automatically by Eclipse when the project was created, but we changed the view in DraggableSymbols set by the argument of setContentView() from the default R.layout.main to our own Java-created view object.
The left figure corresponds to the initial state, before anything has been dragged. In the right figure the green and red symbols already have been dragged to new positions by touching with the finger on a touchscreen (in this case the screen of a Motorola Backflip phone) and dragging to the new position. The yellow symbol is in the process of being dragged to a new position, so a dynamically updated readout of its position in pixels is being displayed as it is being dragged. Also, you should find that nothing happens if you press or drag on the screen background instead
eagle.phys.utk.edu/guidry/android/DraggableSymbols.html 6/9
11/06/2012
Draggable Symbols I
How It Works
The two classes defined in this project are heavily commented, so you should be able to understand what the code is doing by reading through it with systematic attention to the documentation. But some of the comments are a little terse, so let's give a somewhat less abridged version here.
DraggableSymbols
The class DraggableSymbols is the entry point for the app (notice in AndroidManifest.xml that it is the only Activity registered), and extends Activity, as is normal. However, we have replaced the usual specification of the initial screen layout through an XML resource file by the SymbolDragger instance view, which is subclassed from View, in the last three lines of the file. Thus our layout is going to be defined by the Java class SymbolDragger described below. We also have set up some arrays in DraggableSymbols that will hold the initial positions of the draggable symbols that we wish to place on the screen (the arrays X and Y, which hold pixel coordinates as floats). Finally, we have set up an array symbolIndex that holds the integer references to the Drawable image resources that we placed in the res/drawable-hdpi folder. For example, R.drawable.red_square is a reference to the file res/drawablehdpi/red_square.png that the class SymbolDragger will use to access this image resource. These arrays of data are passed as arguments to the constructor of SymbolDragger that we instantiate as the screen view.
SymbolDragger
The Java class SymbolDragger, through the view instance created by DraggableSymbols, does most of the work. It
Defines the screen layout. Listens for finger gestures on the touch screen (no, not that kind of finger gesture!). Implements the appropriate actions in response to the detected gestures.
Let's now describe briefly the main blocks of code that accomplish these tasks in SymbolDragger.
1. The SymbolDragger constructor copies the arrays passed to it from DraggableSymbols into its own local arrays and uses that information to construct additional arrays of information like the dimensions of images, and then uses that to produce the array symbols, which contains objects of type Drawable that will correspond to the visual representation of symbols to be displayed and manipulated onscreen. Finally the constructor sets up the Paint object that will control formatting during screen redraws. 2. The processing of events is implemented by overriding the onTouchEvent(MotionEvent ev) method inherited from View, which processes touch-screen motion events. These correspond to objects of the MotionEvent class, which are used to report movement (mouse, pen, finger, trackball) events. TheMotionEvent method getAction() returns the kind of action being performed as an integer constant of the MotionEvent class, with possible values ACTION_DOWN, ACTION_MOVE, ACTION_UP, and ACTION_CANCEL:
ACTION_DOWN indicates that a pressed gesture has started, with the motion containing the initial starting location. The MotionEvent methods getX() and getY() can be used to retrieve the x and y
coordinates.
ACTION_MOVE indicates that a change has happened during a press gesture between ACTION_DOWN and ACTION_UP. Again, the methods getX() and getY() can be used to retrieve
the x and y coordinates after the change. Although we won't use this functionality here, intermediate
eagle.phys.utk.edu/guidry/android/DraggableSymbols.html 7/9
11/06/2012
Draggable Symbols I
points between the initial down and up events can also be retrieved (see the getHistorySize() and the various getHistorical...() methods of MotionEvent).
ACTION_UP indicates that a pressed gesture has finished; the motion contains the final release
location, as well as any intermediate points since the last down or move event.
ACTION_CANCEL indicates that the action has been canceled. We shall not worry about these
events. 3. The class then uses a switch statement on these possible MotionEvent constants returned by getAction() to process the different possibilities. For ACTION_DOWN (press events) the coordinates of the touch event are retrieved using getX() and getY() and compared with the bounding boxes for the symbols onscreen to see which (if any) of the symbols was touched. If the touch was on a symbol (symbolSelected not equal to -1), the initial coordinates for that symbol are recorded for future reference. An ACTION_MOVE (dragging) event is processed only if the press event preceding it corresponded to touching a symbol and not the background. In that case the boolean isDragging is set to true, enabling the onscreen position readout defined in the method drawBackground, the new position is retrieved using getX() and getY(), and the corresponding symbol position is updated. Finally, the method invalidate() inherited from View is called to request a redraw of the screen. If the constant returned is ACTION_UP (finger-up event), isDragging is set to false to halt the display of position and invalidate() is called to request a redraw. 4. The onDraw(Canvas) method inherited from View is overriden to define the look of the screen. This method will be called each time the screen is redrawn. The draw is on the Canvas object, with formatting controlled by the Paint object. Basically, onDraw calls drawBackground to draw all of the screen except the draggable symbols, and then draws all the onscreen draggable symbols at their current positions by using the translate(dx,dy) method of Canvas to translate by dx in the x coordinate and dy in the y coordinate from their previous position. 5. The drawBackground(canvas, paint) method has the task of drawing everything except the draggable symbols. It first draws the header bar and then the background for the main stage, and finally draws a coordinate readout on the screen if one of the symbols is currently being dragged. Since drawBackground is called before any draggable symbols are drawn, the symbols will always be above anything in the background.
When to redraw the screen is under the control of Android, but the invalidate() method of View requests a redraw (through a call to onDraw(Canvas), if the screen is visible) as soon as possible.
The View method invalidate() marks the entire screen as needing a redraw. The overloaded form invalidate(Rect dirtyRectangle) marks only the portion of the screen defined by the Rect dirtyRectangle as "dirty" and in need of a redraw. Use of this latter form can be important in achieving rapid and smooth response if only a fixed portion of a complex display is changing because of some action. In our example, we have only a few symbols that can be dragged anywhere on the screen, so we request a redraw of the entire screen each time the status of a symbol changes.
This completes the basic demonstration of how to drag some symbols around the screen. We shall now go on to add some additional features.
eagle.phys.utk.edu/guidry/android/DraggableSymbols.html
8/9
11/06/2012
Draggable Symbols I
The project for the application as described to this point is archived at the link DraggableSymbols.
eagle.phys.utk.edu/guidry/android/DraggableSymbols.html
9/9