Android ScaleGestureDetector example

I spend  quite some time to work out how the ScaleGestureDetector on Android works.

However I could not find a good example on the net. So here I post my test code in the hope that it might be useful for someone else:

public class MyTextView extends TextView implements OnTouchListener,OnScaleGestureListener {
ScaleGestureDetector mScaleDetector = new ScaleGestureDetector(getContext(), this);
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.d("MytextView", "MyTextView");
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
Log.d("MytextView", "onScale");
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
Log.d("MytextView", "onScaleBegin");
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
Log.d("MytextView", "onScaleEnd");
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("MytextView", "onTouch");
if(mScaleDetector.onTouchEvent(event)) return true;

return super.onTouchEvent(event);
}
}

The trick is to generate the ScaleGestureDetector and call it from the ontouch method. The Detector will then call the scale… methods if a ScaleGesture is detected. Now just register the OnTouch callback this object and you are done:

public class ScaleActivity extends Activity {
public MyTextView mytextview;
public ScaleGestureDetector scaledetector;

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

mytextview=(MyTextView) findViewById(R.id.TextView);
mytextview.setOnTouchListener(mytextview);
scaledetector=new ScaleGestureDetector(this, mytextview);
}
}

Pretty simple.