我在这个视图中创建了一个视图,我想在获取用户触摸屏幕的像素之后显示该框,但是onDraw方法不是将画布更新为触摸屏幕.你们能帮助我吗?
public class PlayView extends View
{
float width,height;
float touchatX, touchatY;
boolean isanyBox;
public void init()
{
isanyBox = false;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
// TODO Auto-generated method stub
width = w/6f;
height = h/6f;
super.onSizeChanged(w, h, oldw, oldh);
}
public PlayView(Context context)
{
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
init();
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
// TODO Auto-generated method stub
isanyBox = true;
touchatX = (event.getX()/6)*6;
touchatY = (event.getY()/6)*6;
return super.onTouchEvent(event);
}
public void onDraw(Canvas canvas)
{
Paint lineColor = new Paint();
lineColor.setColor(Color.BLACK);
//Box property
Paint boxColor = new Paint();
boxColor.setColor(Color.BLUE);
//Draw horizontal lines
for(int i=0; i<6; i++)
{
canvas.drawLine(0, i*height, getWidth(), i*height, lineColor);
}
//Draw vertical lines
for(int j=0; j<6; j++)
{
canvas.drawLine(j*width, 0, j*width, getHeight(), lineColor);
}
// if(isanyBox)
// {
canvas.drawRect(touchatX+1, touchatY+2, touchatX+width-1, touchatY+height-2, boxColor);
// }
}
}
最佳答案 put invalidate();进入onTouchEvent,
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
isanyBox = true;
touchatX = (event.getX() / 6) * 6;
touchatY = (event.getY() / 6) * 6;
invalidate();
return super.onTouchEvent(event);
}