I have a main FrameLayout and a collection of balls 5 by 7 (each a View) under it. I added onTouchEvent() to switch colors. But regardless which ball I click, only the bottom right ball responds to my touch event (it was the last one to be drawn). Is there a way to get each ball recognize its own touch event?
A thought: I think this might be happening because I'm inserting each Ball (a View) into the main FrameLayout which is supposed to show only one thing at a time. I think it's like a stack of Views and only the top one is responding. Any ideas?
in the Ball class
public class Ball extends View {
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
...
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
public boolean onTouchEvent(MotionEvent event) {
int eventAction = event.getAction();
if(eventAction == MotionEvent.ACTION_DOWN) {
switchcolor();
this.postInvalidate();
return true;
} else {
return false;
}
}
private void switchcolor() {
mPaint.setColor(touched ? 0xFFFFFFFF : 0xFFA606E2);
touched = !touched;
}
in main Activity
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
...
some loop {
main.addView(new Ball(this, x, y, radius - margin));
}