2014-02-19 138 views
-1

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

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


    }); 
} 

} 
+0

没有给出什么输出?你怎么援引这个? –

+0

我没有看到你调用'OTListener()'调用'setOnTouchListener()'的位置。你是否在其他地方叫它,或者你忘了叫它? – jgriffin

回答

1

试试这个。如果它是视图层次结构中的顶视图,它应该可以工作。 你必须看看event.getAction()如果你想在的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; 
    } 

} 
-2

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

+2

这是错误的。请不要传播虚假信息。 – ElDuderino

+2

@ElDuderino如果你愿意的话,它会更有帮助,你知道,解释*为什么*这是错误的,你应该怎么做。 – Seth

+0

@ElDuderino这是我如何修复它。提交一个更好的答案,我会选择它正确的。 – Molehole