Search code examples
androidonclicklistenerandroid-event

Android: Detect OnClick, and whether another element is on top


Strange one, but I want to do the following:

  • Have a round element about the size of a finger tip in the bottom right of the screen.
  • Have some images come in from the left of the screen, at the same Y position, which move from left to right and eventually overlap the above element.
  • Detect when that first element is touched, AND if an image element is overlapping it.

It's similar to how Dance Dance Revolution, or Guitar Hero works. They line up, you tap at the right time, and something happens.

I know how to set an onClickListener, but does anyone know how to achieve the above?

Cheers, Lee.


Solution

  • So despite receiving down votes (would have been nice to let me know why, so I can avoid whatever it was in the future!), I'm going to post the solution which I eventually worked out on my own. Hopefully this will help someone else one day.

    Note: I changed it a little. I now have ki blasts coming from the right of the screen, which move left, and when an image of Goku is tapped, the code checks if any of the ki blasts are at Goku's X-position, plus or minus 100 (so a 100px radius from Goku's center).

        // Set the touch listener for the image I want as the target
    imgCurrentForm.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
    
                        // Ki Blast image
                        ImageView kiBlast1 = (ImageView) findViewById(R.id.kiBlast1);
    
                        // Current X positions at any point in time
                        float xposForm = imgCurrentForm.getX();
                        float xposKi1 = kiBlast1.getX();
    
                        // Handle the screen touch event
                        int action = event.getAction();
                        switch (action) {
    
                            case MotionEvent.ACTION_DOWN:
    
                                if (currentPowerLevel >= 1 && currentPowerLevel <= 299999) {
    
                                    if (Math.abs(xposForm - xposKi1) <= 100) {
                                        // Do whatever needs to be done if true
                                    } 
                                }
                                break;
                        }
                        return true;
                    }
                });