【问题标题】:Android horizontalscrollview center lockAndroid 水平滚动视图中心锁
【发布时间】:2013-11-28 16:37:37
【问题描述】:

我们如何在使用水平滚动视图滚动时实现中心锁定

我已经看过了 http://krishnalalstha.wordpress.com/tag/horizontal-scrollview-with-auto-center-lock/ 但这不是我需要的,我需要自动中心锁

我有一个具有 3 种不同布局的滚动视图(第一个:全宽,第二个:全宽,第三个:半屏),我也尝试过画廊,但我无法删除左侧和右侧的空间,

谢谢

【问题讨论】:

  • 中心锁定是什么意思?
  • 这就像画廊,当你滚动它时,它总是以最靠近屏幕中心的项目为中心

标签: android horizontalscrollview


【解决方案1】:

你正在寻找的一个例子: http://www.velir.com/blog/index.php/2010/11/17/android-snapping-horizontal-scroll/

在我看来,它的解释非常好,因此您应该能够根据您的用例对其进行调整。

但是:常量 SWIPE_THRESHOLD_VELOCITY 设置得太高。 50 在我的情况下工作。只需尝试一下,直到您满意为止。

编辑: 或者,您可能想要使用 ViewPager。它可能更容易,更适合“画廊”用例。

【讨论】:

  • 我们不是必须为每个项目创建一个片段吗?
  • 当使用 ViewPager 时,是,否则不是。只需考虑哪个选项更适合您的需求。例如,Horizo​​ntalScrollView 将允许用户通过单次滑动滚动多个项目,但更难以很好地实现。
【解决方案2】:

Java:

    horizontalScrollView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                        int horizontalWidth = v.getMeasuredWidth();
                        int horizontalHeight = v.getMeasuredHeight();
                        int centerX = v.getScrollX() + horizontalWidth / 2;
                        int centerY = horizontalHeight / 2;
                        Rect hitRect = new Rect();
                        for (int i = 0; i < horizontalContainer.getChildCount(); i++) {
                            View child = horizontalContainer.getChildAt(i);
                            child.getHitRect(hitRect);
                            if (hitRect.contains(centerX, centerY)) {
                                int x = (child.getLeft() - (horizontalWidth / 2)) + (child.getWidth() / 2);
                                horizontalScrollView.smoothScrollTo(x, 0);
                                break;
                            }
                        }
                        return true;
                    } else {
                        return false;
                    }
                }
            });

xml 在哪里:

<HorizontalScrollView
        android:id="@+id/horizontalScrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginBottom="22dp"
        android:gravity="center_vertical">

        <LinearLayout
            android:id="@+id/horizontalContainer"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal" />
</HorizontalScrollView>

容器可能由 syubykh 的孩子包含,大小不限

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多