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.

5 thoughts on “Android ScaleGestureDetector example

    • What you have to do for scalings depends on what you want to scale. The ScaleGuestureDetector just detects that the user wants to zoom in or out.
      How you implement the scaling is up to you and your application.
      Text needs to be scaled diffrent than pictures.
      There simply is no standard way to scale, at least not when I wrote this demo for the ScaleGuestureDetector.

  1. didnt really help me. im implemented our way in my view and activity. I also see the logs in my logcat (means the detector works) but now the views dont scale….

    • Hi Heiko,

      you are right, this only detects the scale gesture on your device. The scaling itself has to be implemented depending on the content. Maybe there is a library out now that can handle that for you, but at the time I was writing this there simply was no standard scale function.

Leave a Reply