Q:

Line drawing on dragging from one point to another in android

I want to make an app in which when i touch at a point on the screen and drag to another position,a line get drawn on ACTION_UP and then another line from the ACTION_UP position to some other point and so on.But the line we have drawn before should not disappear on drawing a new line.

A:

public class LineDrawerView extends View 
{
    public LineDrawerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }   

    ArrayList<Rect> lines= new ArrayList<Rect>();
    int x1, y1;
    int x2, y2;
    boolean drawing=false;

    @Override
    protected void onDraw(Canvas canvas) 
    {
        super.onDraw(canvas);

        canvas.drawColor(Color.YELLOW);

        Paint p= new Paint();
        p.setColor(Color.BLACK);

        if (drawing)
            canvas.drawLine(x1, y1, x2, y2, p);
        else
            for (int i=0; i<lines.size(); i++)
            {
                Rect currline= lines.get(i);
                canvas.drawLine(currline.left, currline.top, currline.right, currline.bottom, p);
            }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) 
    {
        boolean result=false;
        switch (event.getAction()) 
        {
            case MotionEvent.ACTION_DOWN:
                x1=x2= (int)event.getX();
                y1=y2= (int)event.getY();
                drawing=true;
                result=true;
                break;
            case MotionEvent.ACTION_MOVE:
                x2= (int)event.getX();
                y2= (int)event.getY();
                result=true;
                break;
            case MotionEvent.ACTION_UP:
                x2= (int)event.getX();
                y2= (int)event.getY();
                lines.add(new Rect(x1, y1, x2, y2));
                drawing=false;
                result=true;
                break;
        }

        if (result) invalidate();
        return result;
    }
}

