我的Android应用中有LinearLayout
,我想让它可以向各个方向滚动。我只是使用HorizontalScrollView
和ScrollView
实现了这一点,我在其下放置了布局。
这很好用,但我也想实现双指缩放。 所以我受到了这个问题的启发:Android - zoom in/out RelativeLayout with spread/pinch
我提出了以下布局:
<com.example.ZoomableScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.2"
android:scrollbars="none"
android:background="@android:color/black">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:id="@+id/sheet_layout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>
</HorizontalScrollView>
</com.example.ZoomableScrollView>
内部LinearLayout
的子项是动态添加的(它们在水平TextView
内是简单的LinearLayout
来制作一个简单的表格。
ZoomableScrollView
很简单,看起来像这样:
public class ZoomableScrollView extends ScrollView {
float mScaleFactor = 1.f;
private final ScaleGestureDetector mScaleDetector;
static final float MIN_SCALE = 1f;
static final float MAX_SCALE = 4f;
public ZoomableScrollView(Context context) {
this(context, null, 0);
}
public ZoomableScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ZoomableScrollView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
mScaleDetector = new ScaleGestureDetector(context, new OnScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.w("DEBUG", "On touch event");
boolean retVal = mScaleDetector.onTouchEvent(event);
return super.onTouchEvent(event) || retVal;
}
@Override
protected void dispatchDraw(Canvas canvas) {
Log.w("DEBUG", String.format("Scaling with scale factor %f", mScaleFactor));
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale(mScaleFactor, mScaleFactor);
super.dispatchDraw(canvas);
canvas.restore();
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
private class OnScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
@Override
public boolean onScale(ScaleGestureDetector detector)
{
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(MIN_SCALE, Math.min(mScaleFactor, MAX_SCALE));
Log.w("DEBUG", "OnScale: scale factor: " + mScaleFactor);
invalidate();
return true;
}
}
}
我有两个问题:
LinearLayout
会变小,无法再向左滚动。我想我明白为什么会这样,但我不知道如何改变这种情况,我想我在这里走错了方向。我不介意完全改变布局。最后,我希望它的行为有点像浏览器,你可以在任何地方缩放和滚动(虽然不是很复杂)。对此有一个简单的解决方案吗?