我已经从SurfaceView创建了一个类。我希望当我触摸屏幕时,屏幕将通过调用invalidate()函数来刷新。但是在我的实现中,当我触摸屏幕时,不会调用invalidate()。
这是我的代码。
public class GameBoard extends SurfaceView implements Callback {
private SurfaceHolder holder;
int clicked =0;
public GameBoard(Context context)
{
super(context);
holder = getHolder();
holder.addCallback(this);
setFocusable(true);
requestFocus();
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
Canvas c = holder.lockCanvas(null);
onDraw(c);
holder.unlockCanvasAndPost(c);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
}
public boolean onTouchEvent(MotionEvent event)
{
int action = event.getAction();
if (action==MotionEvent.ACTION_UP)
{
clicked++;
// Canvas c = holder.lockCanvas(null);
// onDraw(c);
// holder.unlockCanvasAndPost(c);
invalidate();
}
return true;
}
@Override
protected void onDraw(Canvas canvas)
{
canvas.drawColor(0xFF00ff00);
Paint p = new Paint();
p.setTextSize(20);
p.setColor( Color.RED );
p.setAntiAlias(true);
canvas.drawText(""+clicked, 100, 500, p);
}
}