代码:
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener {
DrawView drawView;
private GestureDetectorCompat g1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.TRANSPARENT);
setContentView(drawView);
g1 = new GestureDetectorCompat(this,this);
g1.setOnDoubleTapListener(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
g1.onTouchEvent(event);
return super.onTouchEvent(event);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
DrawView.x_touch = e.getX();
DrawView.y_touch = e.getY();
Log.v("id2","message2");
return false;
}
绘图代码:
public class DrawView extends View {
Paint paint = new Paint();
static float x_touch = -1;
static float y_touch = -1;
public DrawView(Context context) {
super(context);
super.setWillNotDraw(false);
paint.setColor(Color.BLACK);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Display mdisp = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point mdispSize = new Point();
mdisp.getSize(mdispSize);
int maxX = mdispSize.x;
int maxY = mdispSize.y;
canvas.drawLine(maxX/3, 0, maxX/3, maxY, paint);
canvas.drawLine(maxX*2/3, 0, maxX*2/3, maxY, paint);
canvas.drawLine(0, maxY/3, maxX, maxY/3, paint);
canvas.drawLine(0, maxY*2/3, maxX, maxY*2/3, paint);
Log.v("id1","message1");
if (x_touch>0 && y_touch > 0)
canvas.drawText("X",x_touch,y_touch,paint);
}
}
在做一些研究时,我发现需要在覆盖setWillNotDraw(false)
或使用onDraw()
时调用dispatchDraw()
。
我已经尝试了两种,但只有一次调用Draw函数。
我是Android开发的新手。
答案 0 :(得分:1)
更改您的代码如下:
public class DrawView extends View {
Paint paint = new Paint();
float x_touch = -1;
float y_touch = -1;
public DrawView(Context context) {
super(context);
super.setWillNotDraw(false);
paint.setColor(Color.BLACK);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Display mdisp = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point mdispSize = new Point();
mdisp.getSize(mdispSize);
int maxX = mdispSize.x;
int maxY = mdispSize.y;
canvas.drawLine(maxX/3, 0, maxX/3, maxY, paint);
canvas.drawLine(maxX*2/3, 0, maxX*2/3, maxY, paint);
canvas.drawLine(0, maxY/3, maxX, maxY/3, paint);
canvas.drawLine(0, maxY*2/3, maxX, maxY*2/3, paint);
Log.v("id1","message1");
if (x_touch>0 && y_touch > 0)
canvas.drawText("X",x_touch,y_touch,paint);
}
public void setXandY(float x, float y) {
x_touch = x;
y_touch = y;
this.invalidate();
}
}
并且:
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
drawView.setXandY(e.getX(), e.getY());
return (true);
}