Jayson Tamayo Jayson Tamayo - 1 month ago 7
Android Question

How to Draw Line in Android by Dragging

I am creating a coaching board. I aim to draw a line between two points. Initial position is in the image below:
enter image description here

If I drag the chip away from the initial position, it should draw a line. When I move the chip, it should always draw a line.

This is what I tried:

case MotionEvent.ACTION_UP:
Toast.makeText(this, "here", Toast.LENGTH_SHORT).show();
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
int startx = 50;
int starty = 100;
int endx = 150;
int endy = 210;
canvas.drawLine(startx, starty, endx, endy, paint);

I put that code inside the ontouchlistener of the chip.
You can download the project here: https://www.dropbox.com/s/ggfbsbkaokj9vxi/CoachingBoard.rar?dl=0


After further examining your code, I believe I have achieved what you'd like.

We're going to go to DrawingView and define a getter for drawCanvas, so we can access our canvas outside of the DrawingView class.

Next we're going to head to Basketball and do the following:

float startX;
float startY;
public boolean onTouch(View view, MotionEvent event) {
    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            startX = event.getRawX();
            startY = event.getRawY();

        case MotionEvent.ACTION_UP:
            Paint paint = new Paint(); //set this as a field in drawView with another getter to avoid garbage collection penalties
            drawView.getCanvas().drawLine(startX, startY, event.getRawX(), event.getRawY(), paint);

What this does: when you pick up the chip it will save the starting coordinates, and when you drop the chip it will draw a line in your drawView canvas from start to end.

You can even draw the lines as a continuous Path so the lines always touch, but that is outside the context of this answer.