Android touch listener drag


Touch and Drag in Android

It’s my pet project to understand the Android platform and start writing applications in Scala onto it. After I obtain the legal aspects of my employment regarding code I produce outdoors of labor I would even have the ability to start delivering code/Android applications/make a websiteOrand so on. For the time being, I am not ready yet to create helpful applications. Hell, I am still exercising the kinks with touch occasions. To that particular finish I have been experimenting with creating a much limited clone from the Alchemy game.

If you have never performed it or seen it, the hyperlink ought to provide enough detail to obtain a concept. From the developer’s perspective there’s hardly any happening. Basically there are several symbols that are attracted towards the screen. By dragging one icon atop another you may produce a new element, i.e. both original symbols disappear and therefore are changed with a new icon. Yes, this can be a very mechanical point of view and absolutely simplified to what’s happening underneath the hood however it works as a good beginning point and goal.

Here’s some sample code that puts a control button on screen (that actually does not have to be there,) draws a symbol in the heart of the vista and enables the consumer to drag the icon around. It consists of an insect and extremely is not blog worthy but I have seen a bazillion SO questions regarding TouchEvents. Hope this can help someone, somewhere&hellip

public class Dragable stretches Activity Known as once the activity is first produced. */
public void onCreate(Bundle savedInstanceState) primary)
final Assets res = getResources()
mTiles = res.getDrawable(R.drawable.tiles)
mDrawHeight = mTiles.getIntrinsicHeight()
mDrawWidth = mTiles.getIntrinsicWidth()
final SurfaceView surf = (SurfaceView)findViewById(
surf.setOnTouchListener( new SurfaceView.OnTouchListener()condition
public boolean onTouch(View v, MotionEvent event) situation MotionEvent.ACTION_Lower:
final int x = (int)event.getX()
final int y = (int)event.getY()
final Rect bounds = mTiles.getBounds()
moving = bounds.intersects(x, y, x+1, y+1)
return true
situation MotionEvent.ACTION_MOVE:
if( moving )

return true
situation MotionEvent.ACTION_UP:
moving = false
return true

return false

final Button addButton = (Button)findViewById(
addButton.setOnClickListener( new OnClickListener()

mDrawTiles = new DrawTiles( surf )

private interface DrawLogic
private class DrawTiles
public void draw(DrawLogic _logic)


The primary.xml file appears like this:


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>