我的 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
的子项是动态添加的(它们是水平 LinearLayout
中的简单 TextView
,用于制作一个简单的表格)。
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;
}
}
}
我有两个问题:
- 缩放不是很流畅,有时 View 会在应该缩放时滚动。这不是什么大不了的 atm。
- 缩放时,
LinearLayout
会变小,您无法再到处滚动。我想我明白为什么会这样,但我不知道如何改变它,我想我在这里走错了方向。
我不介意完全改变布局。最后,我想让它的行为有点像浏览器,您可以在其中缩放和滚动到任何地方(虽然不那么复杂)。有没有简单的解决方案?
最佳答案
至于two dimensional scrollView I had used this one .也许你应该尝试为它添加捏。
关于android - 如何在 Android 中使线性布局可滚动和可缩放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29488673/