SurfaceView implements Runnable Android Code

package cz.okhelp.surfview;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
 
public class MainActivity extends Activity implements OnTouchListener {
	OurView v;
	Bitmap ball, blob;
	float x, y;
	Sprite sprite;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.activity_our_view);
		v = new OurView(this);
		v.setOnTouchListener(this);
		ball = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
		x = y = 0;
		setContentView(v);
	}
 
 
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		v.pause();
	}
 
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		v.resume();
	}
 
	public class OurView extends SurfaceView implements Runnable {
		Thread t = null;
		SurfaceHolder holder;
		boolean isItOK = false;
 
		public OurView(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
			holder = getHolder();
		}
 
		public void run() {
			// TODO Auto-generated method stub
			while (isItOK == true) {
				// perform canvas drawing
				if (!holder.getSurface().isValid()) {
					continue;
				}
				// sprite = new Sprite(OurView.this,blob);
				Canvas c = holder.lockCanvas();
				c.drawARGB(255, 100, 100, 10);
				c.drawBitmap(ball, x, y, null);
				// onDraw(c);
				holder.unlockCanvasAndPost(c);
			}
		}
 
		protected void onDraw(Canvas canvas) {
			// sprite.onDraw(canvas);
		}
 
		public void pause() {
			isItOK = false;
			while (true) {
				try {
					t.join();
				} catch (InterruptedException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				break;
			}// end while
		}
 
		public void resume() {
			isItOK = true;
			t = new Thread(this);
			t.start();
		}
	}
 
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			x = event.getX();
			y = event.getY();
 
			break;
		case MotionEvent.ACTION_UP:
			x = event.getX();
			y = event.getY();
 
			break;
		case MotionEvent.ACTION_MOVE:
			x = event.getX();
			y = event.getY();
 
			break;
		}// end switch
 
		return true;
	}
 
}
This entry was posted in Android Examples Code, Bitmap, drawing and tagged , . Bookmark the permalink.


Comments are closed.



8,458 views