How can Android implement double-click to zoom in on an image?

One way to achieve the function of enlarging an image by double-clicking is by using the GestureDetector class in Android to listen for the double-tap gesture.

  1. Add an ImageView control to the layout file for displaying images.
<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="matrix"
    android:src="@drawable/image" />
  1. In the code of an Activity or Fragment, locate the ImageView and set a touch listener.
ImageView imageView = findViewById(R.id.imageView);

GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onDoubleTap(MotionEvent e) {
        // 在此处处理双击事件
        if (imageView.getScaleX() != 1 || imageView.getScaleY() != 1) {
            // 图片已经放大,将其恢复为原始大小
            imageView.setScaleX(1);
            imageView.setScaleY(1);
        } else {
            // 图片未放大,将其放大为原始大小的两倍
            imageView.setScaleX(2);
            imageView.setScaleY(2);
        }
        return true;
    }
});

imageView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        gestureDetector.onTouchEvent(event);
        return true;
    }
});

In the above code, we use the GestureDetector class to listen for double tap gestures. When the double tap event occurs, we check the scaling ratio of the ImageView. If it is already enlarged, we restore it to its original size; if not enlarged, we enlarge it to twice its original size. Finally, we set the listener to the ImageView’s touch event.

In this way, when users double-click on the image, they can easily zoom in and restore the image.

bannerAds