Google Androidでタッチイベントを拾う

ベローチェにて。本日2回目。

タッチイベントを拾うには、android.view.ViewのonTouchEvent()をオーバーライドすればいいみたい。onTouchEventの引数のMotionEventに、座標とタッチ種別を取得するメソッドがあり、これを表示させてみた。

package com.example.andrloid.touchscreen;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class TouchScreen extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TouchView touchView = new TouchView(this);
        setContentView(touchView);
    }
}

class TouchView extends View {
	private int touchX = 0;
	private int touchY = 0;
	private int touchAction;
	
	public TouchView(Context context) {
		super(context);
		setFocusable(true);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		touchX = (int)event.getX();
		touchY = (int)event.getY();
		touchAction = (int)event.getAction();
		invalidate();
		return true;
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		final int TEXT_SIZE = 16;
		
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setTextSize(TEXT_SIZE);
		paint.setColor(0xFFFFFFFF);
		
		canvas.drawText("Touch (x,y) = ("+touchX+","+touchY+")", 0, TEXT_SIZE, paint);
		
		String action = "NONE";
		if (touchAction == MotionEvent.ACTION_UP) {
			action = "ACTION_UP";
		}
		else if (touchAction == MotionEvent.ACTION_DOWN) {
			action = "ACTION_DOWN";
		}
		else if (touchAction == MotionEvent.ACTION_MOVE) {
			action = "ACTION_MOVE";
		}
		else if (touchAction == MotionEvent.ACTION_CANCEL) {
			action = "ACTION_CANCEL";
		}
		canvas.drawText("Touch Action : "+action, 0, TEXT_SIZE*2, paint);
	}
}