如何缩放ViewGroup?

How to zoom ViewGroup?

我需要创建用户可以缩放的视图。我将在视图寻呼机中显示此组件的列表。所以我可以t do scaling in activity. That解释为什么我创建了扩展 RelativeLayout 的自定义视图。

public class JsonRelativeLayout extends RelativeLayout {

private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;

public JsonRelativeLayout(Context context) {
    super(context);
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());

}

public JsonRelativeLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}

public JsonRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    mScaleDetector.onTouchEvent(event);
    return true;
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor);
    //...
    //Your onDraw() code
    //...
    canvas.restore();
}

private class ScaleListener extends SimpleOnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        mScaleFactor *= detector.getScaleFactor();

        // Don't let the object get too small or too large.
        mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));

        invalidate();
        return true;
    }

}

但是 onScale 方法不起作用。我也不知道为什么。

要缩放视图组,您需要扩展 ScrollView 并覆盖 dispatchTouchEvent 和 dispatchDraw。