Invalidate()不刷新屏幕

时间:2014-02-19 20:31:06

标签: java android ontouchlistener invalidation

我想让它按下屏幕移动我的矩形。监听器将输出提供给控制台,但它不会使屏幕无效。

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;
        }


    });
}

}

2 个答案:

答案 0 :(得分:3)

试试这个。如果它是视图层次结构中的顶视图,它应该工作。 如果你想在onTouchEvent()中做更高级的东西,你必须检查event.getAction()......

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;
    }

}

答案 1 :(得分:-2)

在另一种方法中使用invalidate()不起作用。如果要从其他方法刷新活动,则需要使用postinvalidate()。