2015-06-28 107 views
0

我正在实现一个简单的自定义视图,基本上是为了获得一个android canvas的挂件。这是一个简单的tictactoe板。onTouchEvent没有得到执行

这是自定义视图类:

public class BoardInterface extends View implements View.OnTouchListener{ 

    private int board_width, board_height; 
    private final Context context; 

    public BoardInterface(Context context) { 
     super(context); 
     this.context = context; 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     board_width = canvas.getWidth(); 
     board_height = canvas.getHeight(); 


     Paint paint = new Paint(); 
     paint.setColor(Color.BLUE); 
     paint.setStyle(Paint.Style.STROKE); 
     paint.setStrokeWidth(20); 

     canvas.drawLine((board_width/5)*2, (board_height/6), (board_width/5)*2, ((board_height/6)*5), paint); 
     canvas.drawLine(((board_width/5)*3), (board_height/6), ((board_width/5)*3), ((board_height/6)*5), paint); 

     canvas.drawLine((board_width/6), ((board_height/7)*3), ((board_width/6)*5), ((board_height/7)*3), paint); 
     canvas.drawLine((board_width/6), ((board_height/7)*4), ((board_width/6)*5), ((board_height/7)*4), paint); 

     super.onDraw(canvas); 
    } 

    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     int x, y; 
     Log.d("TOUCH", "WORKS"); 
     if (event.getAction() == MotionEvent.ACTION_DOWN) { 
      x = (int) Math.floor(event.getX()); 
      y = (int) Math.floor(event.getY()); 
      Toast.makeText(context, String.valueOf(x) + "," + String.valueOf(y), Toast.LENGTH_SHORT).show(); 
     } 
     return super.onTouchEvent(event); 
    } 
} 

我给自己定一个OnTouchListener并覆盖到展示一个简单的烤面包。 屏幕上没有任何东西出现,即toas,也不会在logcat中获得Log.D()消息。

我在这里错过了什么?

回答

1

尝试重写,而不是onTouch方法下面的方法。

@Override 
public boolean onTouchEvent(MotionEvent event){....} 

如果触摸事件仍然没有得到地方在你的构造

setClickable(True); 
0

上述解决方案的工作称为呼叫。

我也找到了一个解决方案,只是对我的代码做了一个修改[在构造函数中添加了一行]。

public BoardInterface(Context context) { 
     super(context); 
     this.context = context; 
     setOnTouchListener(this); 

}

添加setOnTouchListener(this);后onTouch()方法被执行得很好。