How to make zoomable scrollview?

后端 未结 2 1068
难免孤独
难免孤独 2020-12-08 05:29

In my android application I need to create activities zoom able. I found useful code for zooming linear layout here . But in my application couple of activities start with s

2条回答
  •  无人及你
    2020-12-08 06:07

    Ok. After plowing the net, finally found my answer. I found onTouchEvent() for scrollview does not work so I have to use dispatchTouchEvent() instead of onTouchEvent(). At the top you can see my xml code (in my question) an here is my Activity code of course with comments.

        // step 1: add some instance
    private float mScale = 1f;
    private ScaleGestureDetector mScaleDetector;
    GestureDetector gestureDetector;
    
    //step 2: create instance from GestureDetector(this step sholude be place into onCreate())
    gestureDetector = new GestureDetector(this, new GestureListener());
    
    // animation for scalling
    mScaleDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener() 
        {                                   
            @Override
            public boolean onScale(ScaleGestureDetector detector) 
            {
                float scale = 1 - detector.getScaleFactor();
    
                float prevScale = mScale;
                mScale += scale;
    
                if (mScale < 0.1f) // Minimum scale condition:
                    mScale = 0.1f;
    
                if (mScale > 10f) // Maximum scale condition:
                    mScale = 10f;
                ScaleAnimation scaleAnimation = new ScaleAnimation(1f / prevScale, 1f / mScale, 1f / prevScale, 1f / mScale, detector.getFocusX(), detector.getFocusY());
                scaleAnimation.setDuration(0);
                scaleAnimation.setFillAfter(true);
                ScrollView layout =(ScrollView) findViewById(R.id.scrollViewZoom);
                layout.startAnimation(scaleAnimation);
                return true;
            }
        });
    
    
    // step 3: override dispatchTouchEvent()
     @Override
     public boolean dispatchTouchEvent(MotionEvent event) {
        super.dispatchTouchEvent(event);
        mScaleDetector.onTouchEvent(event);
        gestureDetector.onTouchEvent(event);
        return gestureDetector.onTouchEvent(event);
     }
    
    //step 4: add private class GestureListener
    
    private class GestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
        // event when double tap occurs
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            // double tap fired.
            return true;
        }
    }
    

    Thanks a lot.

提交回复
热议问题