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.
这是我的自定义视图:
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 具有类似的属性,除了方向和爆炸方法(用于沿方向移动它)和动画标志(用于阻止其移动)之外。
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();
}
我的布局xml如下:
<?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" />
我将 BallView 和 SmallBall 添加到活动类中,如下所示:
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);
我在不同位置添加多个 BallView 及其相对的 SmallBall 数组。现在,无论我点击屏幕上最后添加的 BallView 的哪个位置,都会发生什么情况开始爆炸。之后倒数第二个,依此类推。所以这里有两个问题:
- 为什么无论我点击屏幕的哪个位置都会调用 onClick/onTouch 事件?它应该只在我单击特定的 BallView 时调用侦听器事件。
- 其次,为什么 BallView 开始以与添加到布局相反的方式爆炸?
我的监听器类:
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.