You should override the onTouch method in the TokenView class instead.
Canvas is just the place where things of the view are drawn.
You should write something like this in your TokenView class:
private Cell bufferCell;
@Override
public boolean onTouchEvent(MotionEvent event)
{
Cell cell = getCell(event);
if (cell != null)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
if (cell != bufferCell)
bufferCell = cell;
// DO STUFF HERE.
// THE PLAYER HAS JUST TOUCHED A CELL.
// invalidate();
break;
case MotionEvent.ACTION_MOVE:
if (cell != bufferCell)
{
bufferCell = cell;
// Continue Pan
// DO STUFF HERE
// THE PLAYER'S FINGER IS ON A DIFFERENT CELL NOW, AND MOVING
// invalidate();
}
break;
case MotionEvent.ACTION_UP:
// Commit Pan
bufferCell = null;
// DO STUFF HERE
// THE PLAYER HAS TAKEN HIS FINGER OFF THE VIEW
// invalidate();
break;
}
}
return true;
}
private Cell getCell(MotionEvent event)
{
int motionX = (int) event.getX();
int motionY = (int) event.getY();
if (motionX > 0 && motionX < sizeOfGrid && motionY > 0
&& motionY < sizeOfGrid)
{
int rowIndex = motionY / currentSizeOfCell % rowCount;
int columnIndex = motionX / currentSizeOfCell % columnCount;
return cellArray[rowIndex][columnIndex];
}
return null;
}
Call invalidate()
in order to redraw the view.
And don't do Game game = new Game();
inside the onDraw()
method of TokenView.
It will just keep on creating new Games while you draw stuff, and you will not get any expected behavior.
I used a bufferCell
variable which will help reduce the amount of time your logic based methods will be called, because as the player moves his finger over the grid, the cell need not change. Only when it changes, calls to appropriate methods will be fired, if you follow the above mentioned code design.
Also read about as to how to create custom views in Android.
Main methods to override are onDraw()
, onSizeChanged()
, and onMeasure()
.
Hope that helps.