I just started programming in android and I want to draw a line that connects buttons that I click on. I have a gridLayout with a lot of buttons that are defined in the main XML file. I would like to have a straight line drawn from the center of the first clicked button to the next button I push, and so on (sometimes ending at the first button I clicked, so it makes some shape). I have done a lot of research on canvases, animations but can’t figure out where to start. Any help would be greatly appreciated – thanks.
RG
P.S. I would eventually like to animate the connecting lines, but first things first.
The best way to do the drawing would be to override the
draw-method of yourGridLayout. Notably not theonDrawmethod, since that one gets called before your child views are drawn and would thus put your lines into the background. Remember to call the super method before doing your drawing.After the first layout pass (i.e. after
onLayouthas been called at least once) the positions of your buttons should be initialized. You can get their relative positions to their parent by callinggetLeft,getTopetc. on them. You can use that to calculate their center coordinates.You will have to tell your
GridLayoutsomehow on which buttons to draw the lines. Easiest way would probably be to give each button anOnClickListener, and tell their parent (getParent) that it was clicked and should thus start drawing lines accordingly, for example by building up a set of line objects with the coordinates of the clicked buttons. To force a redraw of theGridLayoutafter each click you can callinvalidateon it.