我有一个从ScrollView
. 我想要做的是用这个类实现捏缩放,我想用它缩放到ScrollView
的孩子并根据需要滚动缩放的内容。UIScrollView
基本上,我想要与iOS 类具有相同的行为(这是一个耻辱,Android 不提供像 iOS 那样的任何内置缩放功能,我们必须从头开始编写所有内容)。我有一个ScaleGestureListener
班级内部ScrollView
,当我收到onScale
事件时,我更新了内部子视图的布局尺寸:我将布局宽度和高度乘以我收到的比例因子ScaleGestureListener
. 困扰我的是 ScrollView 不会根据其子项的新尺寸更新其滚动条。例如,如果 child 的宽度变得大于ScrollView
's,它就不会显示水平滚动条。我在滚动视图及其子视图上都调用了invalidate
and ,但它们失败了。requestLayout
下面我给出我的代码:
public class PinchZoomScrollView extends ScrollView{
private ScaleGestureDetector mScaleDetector;// = new ScaleGestureDetector(context, new ScaleListener());
private float mScaleFactor = 1.0f;
private float referenceTextSize;
private static final float MIN_ZOOM_AMOUNT = 1.0f;
private static final float MAX_ZOOM_AMOUNT = 2.0f;
private float refChildWidth;
private float refChildHeight;
private boolean shownForTheFirstTime = true;
//private View content;
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
private WeakReference<PinchZoomScrollView> containerRef;
public ScaleListener(PinchZoomScrollView container)
{
super();
containerRef = new WeakReference<PinchZoomScrollView>(container);
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(MIN_ZOOM_AMOUNT, Math.min(mScaleFactor, MAX_ZOOM_AMOUNT));
//Get Child object
View content = containerRef.get().getChildAt(0);
if(shownForTheFirstTime)
{
shownForTheFirstTime = false;
refChildWidth = content.getWidth();
refChildHeight = content.getHeight();
}
LayoutParams params = new LayoutParams(Math.round(mScaleFactor*refChildWidth), Math.round(mScaleFactor*refChildHeight));
content.setLayoutParams(params);
System.out.println("this.width="+containerRef.get().getWidth());
System.out.println("content.width="+Math.round(mScaleFactor*refChildWidth));
content.invalidate();
content.requestLayout();
containerRef.get().updateViewLayout(content, params);
containerRef.get().invalidate();
containerRef.get().requestLayout();
return true;
}
}
public PinchZoomScrollView(Context context)
{
super(context);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener(this));
}
public PinchZoomScrollView(Context context, AttributeSet attrs)
{
super(context,attrs);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener(this));
}
public PinchZoomScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context,attrs,defStyle);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener(this));
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
super.onTouchEvent(ev);
mScaleDetector.onTouchEvent(ev);
return true;
}
}
长话短说,我需要 ScrollView 根据其子项的更新大小更新其滚动条,每次用户进行缩放时。
提前致谢