Question

I'm working on an app that has a canvas with a bunch of little images that the user can drag around, and a "box" that the user will drag from to create new image objects or drag an existing image to it, and it will remove it.

What is the best way to detect if the user has touched an area, or an image on the screen? The first thing that comes to mind is obviously comparing the touch coordinates with each object's coordinates, but that seems a little cumbersome. Is there a better, or built in way?

Thanks

Was it helpful?

Solution

The View class in Android has an onClickListener which you can use to detect when the user clicks on a View. If you implement your 'images' (as you call them) as Views you can simply add a click listener to each to find which view was clicked. Add the listener like this:

// Get a reference to the view from xml (or if you 
// have created it dynamically, just use that)
View imageView = findViewById(R.id.my_view);
imageView.setOnClickListener(new OnClickListener()
{

  @Override
  public void onClick(View v)
  {
    // Do stuff with view (the View v that is passed is the View that was touched)
    doStuff(v);  
  }
});

OTHER TIPS

It depends on how complicated your interface is, but basically if you override onTouchEvent that will get you the coordinates you were referring to.

In order to find what was touched, without going through every object, you could find ways to simplify this, such as by splitting your screen into perhaps 8 grids, and know which grid(s) every object is in, so that when the screen is touched then you can find the objects that may be in that grid, and so you will have fewer items to look through.

For a brief answer on how to use onTouchEvent you can look at:

http://androidforums.com/android-games/210019-touch-event-image-made-canvas.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top