tags:

views:

494

answers:

1

can anybody tell how to draw a line in android give example

Thanks

+4  A: 

this one draws 2 lines which form a cross on the top left of the screen:

DrawView.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);
        paint.setColor(Color.BLACK);
    }

    @Override
    public void onDraw(Canvas canvas) {
            canvas.drawLine(0, 0, 20, 20, paint);
            canvas.drawLine(20, 0, 0, 20, paint);
    }

}

The activity to start it:

StartDraw.java

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

public class StartDraw extends Activity {
    DrawView drawView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        drawView = new DrawView(this);
        drawView.setBackgroundColor(Color.WHITE);
        setContentView(drawView);

    }
}
Martin
+1 but the OnTouchListener could be removed because it is never used and not important for this example...
WarrenFaith
you're absolutely right - I'll edit the example to get rid of it
Martin
if i want add a line in some other activity like R.layout.main How can i add?
the layout of your activity has to contain a View object - then it's no problem. You just need a View object to draw on
Martin
I want to draw a straight line how can i give the value startx start y stopx stopy?
actually you can find that in the android developer reference, drawLine() has the following arguments: drawLine(float startX, float startY, float stopX, float stopY, Paint paint)
Martin