Wale Bear
Wale Bear

Reputation: 25

Why is my rectangle not updating in my canvas method?(android java)

So I made a painting class which has got an ontouchevent method where i set the xpos of my rectangle to the xpos of the touch event but the rectangle isnt moving! how can I correct that? rectangle class:

public class myRectangle{
public int xpos;
public int ypos;
public int size;
private Paint paint;
public myRectangle(){
    size = 40;
    paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.BLUE);
}
public void drawRectangle(Canvas c,int  x, int y){
    c.drawRect(x, y, size, size, paint);
}

}

and my paint view:

public class Painting extends View {
myRectangle player;
float x;
float y;
public Painting(Context context) {
    super(context);
    player = new myRectangle();
    // TODO Auto-generated constructor stub
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub
    x = event.getX();
    y = event.getY();
    String s = Float.toString(event.getX());
    String c = Float.toString(event.getX());

    Log.d(c, s);
    return super.onTouchEvent(event);
}

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    player.drawRectangle(canvas, (int)x, (int)y);

}

} I can also post the main activity if needed

Upvotes: 2

Views: 438

Answers (1)

Blackbelt
Blackbelt

Reputation: 157447

the only thing missing is the invalidate() call in your onTouchEvent. invalidate() schedule a draw

Upvotes: 1

Related Questions