Steel Nation
Steel Nation

Reputation: 520

Attaching Click-Handler to canvas.drawRect() Object

I am coding a tetris like game and am wondering if there is an easier way to track clicks.

The game board is a 6 by 8 grid of rectangles. I have a class GameBoard that extends View. Here I override the onDraw(Canvas canvas) method and draw the board via a bunch of canvas.drawRect(30,30,80,80,paint) calls.

Is there an easy way to hook up a handler to tell me which rectangle has been clicked? In .net you can use rect.contains(Point p).

Or am I just stuck doing the mat to figure out what rectangle a given point is in?

Upvotes: 1

Views: 4784

Answers (1)

SQLiteNoob
SQLiteNoob

Reputation: 3022

You can try using rect.contains(int x, int y) inside an onTouch() to find it.

Android Docs: http://developer.android.com/reference/android/graphics/Rect.html#contains(int,int)

SO answers: "In your onTouchEvent() just capture the x and y values and you can use the contains(int x, int y) method in the Rect class. If contains(x, y) returns true, then the touch was inside the rectangle and then just create the intent and start the new activity."

from Allowing rectangle to be clickable - android

Also: Android: How to check if a path contains touched point?

Upvotes: 4

Related Questions