James andresakis
James andresakis

Reputation: 5415

Android-How to make moving onscreen objects extend Button

In an app Im working on I have a class that extends a surface view and another that handles all calculations to figure out where and when objects should be drawn onscreen. Right now I have a sort of hacky way of registering screen clicks where a list of objects is parsed through on each click and the closest object takes the click. This works when there is only 3 or 4 objects onscreen but when I have more the clicks register for the wrong objects.

What Im trying to do is to make the onscreen objects extend the button class so I can just pass a MotionEvent to them when they are clicked. But because of the way that the classes I have are set up its a bit confusing to me at the moment on how this could be done.

Does anybody possible know of any tutorials that deal with extending the button class to use with moving onscreen objects?

Upvotes: 0

Views: 1146

Answers (2)

Eli Konky
Eli Konky

Reputation: 2717

I think you kind of mixing stuff. Button is usually used in layout (the xml layout stuff). When you use surface view you (most likely) need to implement your own "button". However, it is probably possible to just overlay a frameview on top of your surface view and place the button on that view.

Upvotes: 1

phil917
phil917

Reputation: 113

If I understand correctly, you're trying to determine which object drawn to the screen has been clicked?

I know this isn't exactly what you asked for but when I've implemented a custom view the past, I've typically handled click detection like this:

I get the x and y coordinates of the objects that you want to be clickable. In your onTouchEvent(MotionEvent event) method within your SurfaceView class, have some if statement that checks whether the x and y of the click is within the bounds of your object.

Here's some code to better illustrate what I'm saying:

@Override
public boolean onTouchEvent(MotionEvent event) 
{
    // If the user touches the space occupied by object1
    if(event.getAction() == MotionEvent.ACTION_DOWN 
            && event.getX() <= object1.xPosition + object1.width 
            && event.getX() >= object1.xPosition
            && event.getY() >= object1.yPosition 
            && event.getY() < object1.yPosition + object1.height)
    {
            // The click was in the bounds of object1's current location
        object1.doSomething();
    }
    // ......
}

Hopefully this makes sense and is somewhat helpful.

Upvotes: 1

Related Questions