Question

I want to make it so that pressing the screen moves my rectangle. The listener gives output to console but it doesn't invalidate the screen.

public class DrawView extends View{
    Paint paint = new Paint();
    static int x = 20;
    static int y = 20;

public DrawView(Context context){
    super(context);
    paint.setColor(Color.GREEN);
}

@Override
public void onDraw(Canvas canvas){
    canvas.drawRect(x,y,100,100,paint);
}

public void OTListener(){
    setOnTouchListener(new OnTouchListener(){
        public boolean onTouch(View DrawView, MotionEvent e){
            x = 100;
            y = 100;
            invalidate();

            return false;
        }


    });
}

}
Was it helpful?

Solution

Try this. It should work if it is the top view in your view hierarchy. You'll have to check out event.getAction() if you want to do more advanced stuff in onTouchEvent()...

public class DrawView extends View {

    Paint paintRect = new Paint();
    Paint paintClear = new Paint();
    private Point touch = new Point();

    public DrawView(Context context){
        super(context);
        paintClear.setColor(Color.BLACK);
        paintRect.setColor(Color.GREEN);
    }

    @Override
    public void onDraw(Canvas canvas){
        canvas.drawPaint(paintClear);
        canvas.drawRect(touch.x-50,touch.y-50,touch.x+50,touch.y+50,paintRect);
    }

    private void touch(int x, int y) {
        touch.set(x,y);          
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {       
        touch((int)event.getX(), (int)event.getY());
        return true;
    }

}

OTHER TIPS

Using invalidate() in another method doesn't work. You need to use postinvalidate() if you want to refresh activity from another method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top