Younas Bangash Younas Bangash - 6 months ago 11
Java Question

Drawing lines on activity_main

I am unable to draw the lines on

activity_main
layout using the below code. Do you have any idea what I'm doing wrong?

public class MainActivity extends Activity
{
DrawView drawView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);

drawView = new DrawView(this);
setContentView(R.layout.activity_main);
drawView.requestFocus();

}



}

public class DrawView extends View implements OnTouchListener
{
private static final String TAG = "DrawView";

List<Point> points = new ArrayList<Point>();
Paint paint = new Paint();

public DrawView(Context context)
{
super(context);

setFocusable(true);
setFocusableInTouchMode(true);

this.setOnTouchListener(this);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
paint.setColor(Color.BLACK);



}



@Override
public void onDraw(Canvas canvas)
{
Path path = new Path();
boolean first = true;
for(Point point : points){
if(first)
{
first = false;
path.moveTo(point.x, point.y);
}
else
{
path.lineTo(point.x, point.y);
}
}
canvas.drawPath(path, paint);
}

public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() != MotionEvent.ACTION_UP)
{
Point point = new Point();
point.x = event.getX();
point.y = event.getY();
points.add(point);
invalidate();
Log.d(TAG, "point: " + point);
return true;
}
return super.onTouchEvent(event);
}

class Point
{
float x, y;
float dx, dy;

@Override
public String toString()
{
return x + ", " + y;
}
}
}

Answer

you can use view to draw line in your xml file

           <View android:id="@+id/hline"
            android:background="#ff005d"
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            />