I'm trying to create my first android application, but it's all too mysterious for me, so I am asking.
My program uses FrameLayout
and Circles. When I click background I want a new circle to appear. That's easy. In MainActivity
I just set FrameLayout.setOnTouchListener
. That's OK.
But I also want to delete circle when I touch it. My circles have more properties, so I created my own class and named it Ball. This Ball class extends View
class and implements OnTouchListener
. Than I added method:
boolean onTouch(View arg0, MotionEvent arg1)
It works too. But If I want to catch both events in my program (FrameLayout.onTouch
and Ball.onTouch
) than only one is catched. It does not matter where I click. My program always things that I clicked background.
I do not know what to do with it :(
Balls are added like this (constructor does it):
mPaint.setColor(c);
this.x = x;
this.y = y;
th开发者_开发问答is.r = r;
And constructor is called:
myNewBall = new Ball(x,y,r,c)
And ball is added to FrameLayout:
myLayout.addView(currentBall);
Can you help please?
Does your Ball.onTouch()
return true
? If so, your Ball
will consume the event and the the FrameLayout
won't be notified.
It should return false
to indicate to the framework it should keep calling other handlers. However, this means your Ball
won't get follow-up events related to the onTouch
.
The other alternative is to make your Ball.onTouch()
additionally run the same call (call a common method?) as FrameLayout.onTouch()
.
http://developer.android.com/guide/topics/ui/ui-events.html
onTouch() - This returns a boolean to indicate whether your listener consumes this event. The important thing is that this event can have multiple actions that follow each other. So, if you return false when the down action event is received, you indicate that you have not consumed the event and are also not interested in subsequent actions from this event. Thus, you will not be called for any other actions within the event, such as a finger gesture, or the eventual up action event.
I'm not familiar with FrameLayout etc but it sounds like you'll have to do this:
- Maintain an array or linked list of your ball objects.
- In your click handler, check if the click point is inside any ball.
- If so, remove that ball.
To find out if a click point is within a circle:
ball position is ballx, bally
click position is clickx, clicky
for each ball:
distx = clickx - ballx
disty = clicky - bally
dist = square root of (distx*distx + disty*disty)
if (dist < ball radius) then click is within ball
精彩评论