May 4, 2011

A basic implementation of SurfaceView

SurfaceView provides a dedicated drawing surface embedded inside of a view hierarchy. You can control the format of this surface and, if you like, its size; the SurfaceView takes care of placing the surface at the correct location on the screen.

Access to the underlying surface is provided via the SurfaceHolder interface, which can be retrieved by calling getHolder().

package com.TestSurefaceView;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class TestSurefaceView extends Activity {

MySurfaceView mySurfaceView;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       mySurfaceView = new MySurfaceView(this);
       setContentView(mySurfaceView);
   }
  
   @Override
protected void onResume() {
 // TODO Auto-generated method stub
 super.onResume();
 mySurfaceView.onResumeMySurfaceView();
}

@Override
protected void onPause() {
 // TODO Auto-generated method stub
 super.onPause();
 mySurfaceView.onPauseMySurfaceView();
}

class MySurfaceView extends SurfaceView implements Runnable{
   
    Thread thread = null;
    SurfaceHolder surfaceHolder;
    volatile boolean running = false;

 public MySurfaceView(Context context) {
  super(context);
  // TODO Auto-generated constructor stub
  surfaceHolder = getHolder();
 }

 public void onResumeMySurfaceView(){
  running = true;
  thread = new Thread(this);
  thread.start();
 }

 public void onPauseMySurfaceView(){
  boolean retry = true;
  running = false;
  while(retry){
   try {
    thread.join();
    retry = false;
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  while(running){
   if(surfaceHolder.getSurface().isValid()){
    Canvas canvas = surfaceHolder.lockCanvas();
    //... actual drawing on canvas
   
    surfaceHolder.unlockCanvasAndPost(canvas);
   }
  }
 }
   
   }
}


next:
- Drawing on SurfaceView
- Handle onTouchEvent in SurfaceView
- Draw path on SurfaceView's canvas

4 comments:

  1. How come you create a new thread each time the activity wakes up from a pause?

    ReplyDelete
    Replies
    1. Because I don't want waste system resource, so I kill the thread onPause, in onPauseMySurfaceView(). So I have to create a new one onResume, in onResumeMySurfaceView().

      Delete

Infolinks In Text Ads