views:

46

answers:

1

Hi,

I am trying to drag a view over the screen

FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
final Ball bigball;
bigball = new Ball(this,50,50,25, 0xFFFF0000);
main.addView(bigball);

This draws a red circle on my screen. How and where do I need to implement my touchscreen-handling, if I want it only to trigger if someone touches the red circle rather than the remainder of the screen?

Ball.Java is a separate class:

public class Ball extends View 

I know I could check the coordinates where the user touched the screen and then compare that to where the circle is, but there must be a way to simply check the ID or some other reference of the circle, right?

Everything I have looked at and tried so far would run my code regardless of where the touch started or stopped on the screen. (So I can move the ball, I can draw lines on the screen with my finger and everything. But I cannot tell if I touched the red circle.)

Can anyone expain this to me in simple words, please? (And forgive me for using equally simple words in my question. I no longer feel I have a clue what I'm doing here, and I by now I would just not use big words like "Listener" or "Event" correctly anymore.

Thanks.

A: 

you can override/implement onTouchEvent in Ball class which is extended from View.

public class Ball extends View {
  public boolean onTouchEvent(MotionEvent ev) {
    if(ev.getAction == /*check against all the desired action*/ {
      //handle touch and return true
    return super.onTouchEvent(ev);
}

bhups
Yes, I tohght this should work, too.
Alex
But the function gets called regardless of where I click. Is it possible that my ball simply takes up the entire screen and I've been chasing the wrong type of error?It's a ciclre drawn on a Canvas:
Alex
public class Ball extends View { private float x; private float y; private final int r; private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); public Ball(Context context, float x, float y, int r, int bcolor) { super(context); mPaint.setColor(bcolor); this.x = x; this.y = y; this.r = r; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(x, y, r, mPaint);
Alex
where have you defined the functions and from where are you calling this function?
bhups
Okay, my mistake was that the canvas of the circle took up the entire screen. Everything worked fine - but I was only ever touching the circle-canvas and never the screen itself.I have now used an ImageView and assigned setOnTouchListener to it in the main activity. Works like a charm.Thank you!
Alex