【发布时间】:2015-04-07 09:51:26
【问题描述】:
我的 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 的子级是动态添加的(它们是简单的TextViews 里面的水平LinearLayouts 来制作一个简单的表格)。
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变小,您无法再到处滚动。我想我明白为什么会这样,但我不知道如何改变这种情况,我认为我在这里走错了方向。
我不介意完全改变布局。最后,我希望它的行为有点像浏览器,您可以在其中缩放和滚动任何地方(虽然不那么复杂)。有没有简单的解决方案?
【问题讨论】:
-
旁注:我有点犹豫是否要简单地使用
WebView和 HTML,因为我认为这将提供我需要的一切,但我真的想试一试 Android GUI 的东西: ) -
你找到解决办法了吗?
标签: android scrollview android-linearlayout pinchzoom