Android横向滚动视图中心锁定

3
如何在使用横向滚动视图时实现中心锁定?
我已经查看了这个网址http://krishnalalstha.wordpress.com/tag/horizontal-scrollview-with-auto-center-lock/,但它不符合我的需求,我需要自动中心锁定。
我有一个scrollview,其中包含3个不同的布局(第一个:整个宽度,第二个:整个宽度,第三个:半个屏幕),我也尝试过使用画廊,但无法删除左侧和右侧的空白。
谢谢。

什么是中心对齐? - Subramanian Ramsundaram
就像画廊一样,当你滚动它时,它总是会将最靠近屏幕中心的项目居中。 - TootsieRockNRoll
2个回答

1

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>

容器可以包含任意大小的子元素。

1
这是一个非常符合你要求的示例: http://www.velir.com/blog/index.php/2010/11/17/android-snapping-horizontal-scroll/ 我认为解释得很清楚,所以你应该能够根据自己的用例进行调整。
但是:常量SWIPE_THRESHOLD_VELOCITY设置得太高了。在我的情况下,50就可以了。只需尝试几次,直到满意为止。
编辑: 或者,您可能希望使用ViewPager。它可能更容易,并更适合“画廊”用例。

我们难道不需要为每个项目创建一个片段吗? - TootsieRockNRoll
当使用ViewPager时,是的;否则,不需要。只需考虑哪个选项更适合您的需求。例如,HorizontalScrollView允许用户在单个滑动中滚动多个项目,但实现起来更加困难。 - 0101100101

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接