android中的自定义对象点击问题

Har*_*Joy 6 android click effect

我在android中创建了一个自定义视图以在屏幕上显示球.现在我想要的是当我触摸那个球时它应该分成四个部分爆炸,每个部分应该向上,向下,向左,向右移动不同的四个方向.我知道我必须设置触摸侦听器以检测球上的触摸但是如何创建爆炸效果?这个问题现在解决了.我在屏幕上显示多个球,以便用户可以点击它并将其爆炸.

这是我的自定义视图:

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

具有相似属性的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();
}
Run Code Online (Sandbox Code Playgroud)

我的布局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" />
Run Code Online (Sandbox Code Playgroud)

我将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);
Run Code Online (Sandbox Code Playgroud)

我在不同的位置添加了多个BallView及其相对的SmallBall数组.现在无论我在哪里点击屏幕,最后添加的BallView都会爆炸,会发生什么.在那之后的第二个,等等.所以这里有两个问题:

  1. 无论我在哪里点击屏幕,为什么要调用onClick/onTouch事件?它应该只在我点击特定的BallView时调用监听器事件.
  2. 第二个是为什么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.
    }
Run Code Online (Sandbox Code Playgroud)

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

noo*_*oob 1

我认为您不需要在画布中对所有这些进行硬编码。您可以调用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
}
Run Code Online (Sandbox Code Playgroud)

Explode 方法将根据传递的方向开始更改它们的 x 和 y 坐标。我希望这能为您提供有关如何实施它的提示。