2. Add a new View (SurfaceView) Class. (File -> New -> Class)
3. Add Constructor in the new Class.
public Panel(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
4. Change Activity
setContentView(R.layout.main);
to your new Class
setContentView(new Panel(this));
5a. Add the onDraw for View
@Override public void onDraw(Canvas canvas) { canvas.drawColor(Color.BLACK); canvas.drawBitmap(mBitmap, 10, 10, null); }
public class Panel extends SurfaceView implements SurfaceHolder.Callback { private AnimationThread mThread; public Panel(Context context) { super(context); // TODO Auto-generated constructor stub getHolder().addCallback(this); mThread = new AnimationThread(this); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub if (!mThread.isAlive()) { mThread = new AnimationThread(this); mThread.setRunning(true); mThread.start(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub if (mThread.isAlive()) { mThread.setRunning(false); } }
public void doDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); } }
public class AnimationThread extends Thread {
public AnimationThread() {
// TODO Auto-generated constructor stub
}
// TODO Auto-generated constructor stub
}
private Panel mPanel;
private SurfaceHolder mHolder;
private boolean mRun = false;
public AnimationThread(Panel panel) {
mPanel = panel;
mHolder = mPanel.getHolder();
}
public void setRunning(boolean run) {
mRun = run;
}
@Override
public void run() {
Canvas canvas = null;
while (mRun) {
canvas = mHolder.lockCanvas();
if (canvas != null) {
mPanel.doDraw(canvas);
mHolder.unlockCanvasAndPost(canvas);
}
}
}
}
private SurfaceHolder mHolder;
private boolean mRun = false;
public AnimationThread(Panel panel) {
mPanel = panel;
mHolder = mPanel.getHolder();
}
public void setRunning(boolean run) {
mRun = run;
}
@Override
public void run() {
Canvas canvas = null;
while (mRun) {
canvas = mHolder.lockCanvas();
if (canvas != null) {
mPanel.doDraw(canvas);
mHolder.unlockCanvasAndPost(canvas);
}
}
}
}
沒有留言:
張貼留言