I created a custom view in Android to display the ball on the screen. Now I want, when I touch this ball, it should explode in four parts, and each part should move different four directions, i.e. up, down, left, right. I know that I have to install a touch listener to detect a touch on the ball, but then how to create an explosion effect? This issue has been resolved now . I show several balls on the screen so that the user can click on it and detonate 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, which is a direction and a break method, to move it in the direction and an animation flag to stop it moving.
private final int direction; private boolean anim; public void explode() {
My xml layout 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 add BallView and SmallBall to the 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 add a few BallViews and their relative SmallBall array at different positions. Now, what happens no matter where I click on the screen, the latter added that BallView is starting to explode. After this second and so on. So here are 2 questions:
- Why does it trigger the onClick / onTouch event no matter where I click on the screen? It should only trigger a listener event when I click on a specific BallView.
- And secondly, why does BallView begin to explode in the opposite way, how are they added to the layout?
My listener class:
public void onClick(View v) { BallView ballView = (BallView) v; ballView.setVisibility(View.GONE);
I cut the code due to the character restriction in question.