Michael Zeuner
Michael Zeuner

Reputation: 1776

OnTouch method in OnDraw

I need to set an onTouch method to the rect that I have set up but I dont know how to do this in an OnDraw method. this but I dont know how here my code, Thanks for the help!

public class Tab3 extends View implements OnTouchListener
{
    int x1, x2, y1, y2;
    Rect Rect = new Rect();
    public Tab3(Context context, AttributeSet attrs)
    {
        super (context, attrs);
        x1 = 0;
        x2 = 100;
        y1 = 0;
        y2 = 100;

    }

    @Override
    protected void onDraw(Canvas canvas) 
    {
        // TODO Auto-generated method stub
        super.onDraw(canvas);


        Rect.set(x1, y1, x2, y2);

        Paint blue = new Paint();
        blue.setColor(Color.BLUE);
        canvas.drawRect(Rect, blue);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) 
    {

        return false;
    }
}

Upvotes: 0

Views: 1916

Answers (4)

Phil
Phil

Reputation: 2446

First you can have a lot of problems with

Rect Rect = new Rect();

name it

Rect rect2 = new Rect();

or something like that and not Rect Rect

A small performence tipp

Rect.set(x1, y1, x2, y2);

make this in the

public Tab3(Context context, AttributeSet attrs)
    {
}

because the

  protected void onDraw(Canvas canvas) 
    {

is called every time you make a repaint with

invalidate();

her you check if you press in the rect

if (rect2.contains(event.getX(),event.getY())) {

Upvotes: 1

MikeC
MikeC

Reputation: 735

in your onTouch just put :

if(Rect.contains((int) event.getX(),(int) event.getY())){

i think this is what your asking let me know if its not

Upvotes: 2

Longerian
Longerian

Reputation: 723

in onTouch, you can do the following things:

if(Rect.contains((int) event.getX(), (int) event.getY())) {
//do something
}
return super.onTouch(View v, MotionEvent event);  //call super's method so that system would send event to you only once when you touched it.

Upvotes: 0

jtt
jtt

Reputation: 13541

Read about the MotionEvent class.

Upvotes: 0

Related Questions