Skip to content Skip to sidebar Skip to footer

How To Create Clickable Rectangles?

Im drawing an indoor map using DrawRect method. I want to identify each rectangle by the user's OnTouch Event.How can i make it happen? I want to know if i can use the drawn Rectan

Solution 1:

The canvas will not remember about the shapes you draw on it. You have to keep track of them separatedly. You should fill a list (or some other data structure) with Rect objects ("model" objects), or other custom objects holding the coordinates, dimensions and whatever you need, of the rectangles, and check on touch if the coordinates of the touch are inside of any of these rectangles. E.G. method contains(int x, int y) of Android's Rect will help. In your draw method you then use also these objects.

Solution 2:

I realize this question was asked a while back but i noticed your updated question...

I'm guessing the problem your having is actually your trying to run "startActivity" from a View class.

Firstly if you make a new static void on your activity class like so

publicstaticvoidRectclicked(Context c){
        Intent inte = newIntent(c, SecondActivity.class);
        c.startActivity(inte);
    }

then back on your View class, in your TouchEvent add this into the for loop if a rectangle has been clicked

MainActivity.Rectclicked(getContext());

Solution 3:

Im not sure if this has been answered but i am building something similar. For the construction of the rects i have just manually added each and then used an Rect.intersect() to see if the constructed rects cross the touchpoint. Thats a vague answer but i figure you figured it out, let me know if you didn't:D

Post a Comment for "How To Create Clickable Rectangles?"