Thursday, May 19, 2011

Detect single touch on custom View

In this exercise, we are going to create a custom view, SingleTouchView. With onTouchEvent() overrided to handle single touch event.

Detect single touch on custom View





SingleTouchView.java
package com.exercise.AndroidTouch;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class SingleTouchView extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private float x, y;
private boolean touching = false;

public SingleTouchView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public SingleTouchView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public SingleTouchView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);

if(touching){
paint.setStrokeWidth(1);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(x, y, 75f, paint);
}

}

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
// TODO Auto-generated method stub

switch(motionEvent.getAction()){
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:
x = motionEvent.getX();
y = motionEvent.getY();
touching = true;
break;
default:
touching = false;
}
invalidate();
return true;
}

}


Modify main.xml to include SingleTouchView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.exercise.AndroidTouch.SingleTouchView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>


Do nothing on the main activity code, AndroidTouch.java
package com.exercise.AndroidTouch;

import android.app.Activity;
import android.os.Bundle;

public class AndroidTouch extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}



Download the files.


Related Article:
- Detect Multi touch on custom View

No comments: