我已经在android中创建了一个自定义 View 以在屏幕上显示球。现在我想要的是,当我触摸该球时,它应该爆炸成四个部分,并且每个部分都应沿四个方向(即上,下,左,右)移动。我知道我必须设置触摸监听器来检测对球的触摸,但是如何创建爆炸效果?此问题现在已解决。我正在屏幕上显示多个球,以便用户可以单击它并使其爆炸。

这是我的自定义 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,除了其中一个是direction之外,还有一种爆炸方法(沿方向移动它)和动画标志来阻止它移动。
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添加到 Activity 类中,如下所示:
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.
        }
    

    由于有问题的字符限制,我已经修剪了代码。

    最佳答案

    我认为您不需要在 Canvas 上对所有这些进行硬编码。您可以在Touch Listener中调用ball.setVisibility(View.GONE),并通过对每个小球使用smallBall.setVisibility(View.Visible)来显示4个额外的球。这样,您就可以隐藏大球,并且可以显示小球。
    现在,为了获得运动效果,每个小球中都需要一个方法来传递方向,您可以像这种smallBall.explode(direction)一样调用它。该方法的实现可以是

    explode(int direction){//can be String
      if(direction=NORTH)
         y--;
      //other condition checks
    }
    

    爆炸方法将根据传递的方向开始更改其x和y坐标。
    我希望这会给您一些有关如何实现它的提示。

    09-17 21:16