Add a canvas - Android
I dynamically create a canvas with:
Canvas canvas = new Canvas();
But how can I add it to my LinearLayout?
LinearLayout ll = new Line开发者_开发问答arLayout(this);
You can either do it with a simple addView or if you are doing something more complex like needing a new thread to do your graphics painting then you can add it to your xml layout with a custom SurfaceView
<com.util.MyDraw
android:id="@+id/surfaceView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10px"
android:layout_marginLeft="10px"
android:layout_marginRight="10px"
android:layout_below="@+id/spinner1"
/>
Then create a class called MyDraw that extends SurfaceView and in there you can call your Thread to paint.
package com.util;
public class MyDraw extends SurfaceView implements Callback {
private MyThread myThread;
private SurfaceHolder holder;
private Paint paint;
Path path;
public LinkedList<Integer> list; {
list = new LinkedList<Integer>();
}
public MyDraw(Context context) {
super(context);
holder = getHolder();
holder.addCallback(this);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setColor(Color.GREEN);
path = new Path();
}
public void surfaceCreated(SurfaceHolder holder) {
myThread = new MyThread(holder, this);
myThread.setFlag(true);
myThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
public void surfaceDestroyed(SurfaceHolder holder) {
myThread.setFlag(false);
}
@Override
protected void onDraw(Canvas canvas) {
path.rewind();
path.reset();
if (canvas != null) {
canvas.drawColor(Color.BLACK);
if (list != null && list.size() > 0) {
path.moveTo(0, list.get(0));
int sec;
for(sec = 1; sec < list.size(); sec++) {
path.lineTo(sec, (list.get(sec)/divFactor));
}
canvas.drawPath(path, paint);
}
}
}
This replaces my earlier answer (which was totally off). A Canvas is not something to be added to a layout. (If you're familiar with J2SE, it's the Android analogue to java.awt.Graphics.)
Perhaps you want to add a view where you can do your own drawing (using a Canvas). For this, you can use a SurfaceView or you can define your own custom View class as described here.
setContentView(canvasView); //add canvas view (set canvasView as main view)
linearLayout.addView(canvasView); //linearLayout add canvasView
public class CanvasView extends View{
public CanvasView(Context c){
super(c);
}
public void onDraw(Canvas canvas){
//do your draw methods
}
}
精彩评论