I have created an custom view in android to display ball on screen. Now what I want is when I touch on that ball it should explode in four parts and every part should move different four directions ie up, down, left, right. I know I have to set touch listener to detect touch on ball but then how to create a explode effect?This issue is solved now. I'm displaying multiple balls on screen so that user can click on it and explode them.
Here is my custom view:
public class BallView extends View {
private float x;
private float y;
private final int r;
public BallView(Context context, float x1, float y1, int r) {
super(context);
this.x = x1;
this.y = y1;
this.r = r;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
SmallBall with similar properties except one that is direction and an explode method to move it in direction and animation flag to stop it moving.
private final int direction;
private boolean anim;
public void explode() {
// plus or minus x/y based on direction and stop animation if anim flag is false
invalidate();
}
My layout xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/main_view"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF66FF33" />
I'm adding BallView and SmallBall to activity class as follows:
final FrameLayout mainFrameLayout = (FrameLayout) findViewById(R.id.main_frame_layout);
SmallBall[] smallBalls = new SmallBall[4];
smallBalls[0] = new SmallBall(getApplicationContext(), 105, 100, 10, 1, false);
smallBalls[0].setVisibility(View.GONE);
mainFrameLayout .addView(smallBalls[0]);
// create and add other 3 balls with different directions.
BallView ball = new BallView(getApplicationContext(), 100, 100, 25, smallBalls);
listener = new MyListener(ball);
ball.setOnClickListener(listener);
mainFrameLayout.addView(ball);
I'm adding multiple BallView and their relative SmallBall array at different positions. Now what happens no matter where I click on screen last added BallView starts to explode. After that second last, and so on. So here are 2 issues:
- Why it call onClick/onTouch event no matter where I click on screen? It should only call listener event when I click on particular BallView.
- And second is why BallView starts exploding in reverse manner of how they are added to layout?
My listener class:
public void onClick(View v) {
BallView ballView = (BallView) v;
ballView.setVisibility(View.GONE);
//get small balls associated with this ball.
//loop through small ball and call their explode method.
}
I've trimmed code due to character limitation in question.