/** * Touch Input Demo */ package android.program; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.*; import android.os.Bundle; import android.view.*; import android.view.View.OnTouchListener; public class Game extends Activity implements OnTouchListener { DrawView drawView; //input variables Point touch = new Point(0,0); String inputAction = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); drawView = new DrawView(this); setContentView(drawView); //turn on touch listening drawView.setOnTouchListener(this); } @Override public void onResume() { super.onResume(); drawView.resume(); } @Override public void onPause() { super.onPause(); drawView.pause(); } //touch listener event @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: inputAction = "DOWN"; break; case MotionEvent.ACTION_MOVE: inputAction = "MOVE"; break; case MotionEvent.ACTION_UP: inputAction = "UP"; break; } //remember this touch position touch.x = (int)event.getX(); touch.y = (int)event.getY(); //notify touch handler that we used it return true; } public class DrawView extends SurfaceView implements Runnable { //game loop thread Thread gameloop = null; //surface holder SurfaceHolder surface = null; //thread-safe running var volatile boolean running = false; //asset manager AssetManager assets = null; //constructor method public DrawView(Context context) { super(context); //get the SurfaceHolder object surface = getHolder(); //create the asset manager assets = context.getAssets(); } public void resume() { running = true; gameloop = new Thread(this); gameloop.start(); } public void pause() { running = false; while (true) { try { gameloop.join(); } catch (InterruptedException e) { } } } //thread run method @Override public void run() { while (running) { if (!surface.getSurface().isValid()) continue; //open the canvas for drawing Canvas canvas = surface.lockCanvas(); canvas.drawColor(Color.BLACK); //draw circle at touch position Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setTextSize(24); canvas.drawText("Touch screen to test single touch input", 10, 20, paint); canvas.drawText("Action: " + inputAction, 10, 50, paint); canvas.drawText("Position: " + touch.x + "," + touch.y, 10, 80, paint); if (touch.x != 0 && touch.y != 0) canvas.drawCircle(touch.x, touch.y, 50, paint); //close the canvas surface.unlockCanvasAndPost(canvas); try { Thread.sleep(20); } catch(InterruptedException e) { e.printStackTrace(); } } } } }