horizo​​ntalscrollview gravity

时间:2012-03-25 15:52:58

标签: android horizontalscrollview

如何使horizo​​ntalscrollview移动更靠近屏幕中心的相对对象? 如图所示:

enter image description here

2 个答案:

答案 0 :(得分:0)

Gallery将在窗口中央显示当前项目。有关详细信息,请参阅Gallery tutorial

您可以动态调整项目的间距,以便通过调用setSpacing(int)填充屏幕。 (但是,如果活动在平板电脑上以横向模式显示,那么这就是你想要的吗?那将是一个空白的屏幕。)

答案 1 :(得分:0)

我在新闻解析器示例中找到了解决方案。我的代码:

...

gestureDetector = new GestureDetector(new MyGestureDetector());
        hs = (HorizontalScrollView) findViewById(R.id.hs);
        hs.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                if (event.getAction() == 1)
                {
                    if (hs.getScrollX() > mWidth * 8 + mWidth / 2)
                    {
                        hs.smoothScrollBy(mWidth * 9 - hs.getScrollX(), 0);
                    }
                    else if (hs.getScrollX() > mWidth * (cN - 2)  + mWidth / 2)
                    {
                        hs.smoothScrollBy(mWidth * (cN - 1) - hs.getScrollX(), 0);
                    }
                    else if (hs.getScrollX() > mWidth / 2)
                    {
                        hs.smoothScrollBy(mWidth - hs.getScrollX(), 0);
                    }
                    else
                    {
                        hs.smoothScrollBy(-hs.getScrollX(), 0);
                    }
                    return true;
                }
                return false;
            }
        });
    }


    class MyGestureDetector extends SimpleOnGestureListener {

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            //Log.v("e1.getX()", Float.toString(e1.getX()));
            //Log.v("e2.getX()", Float.toString(e2.getX()));
            //Log.v("velocityX", Float.toString(velocityX));
            if (velocityX > 0) {
                moveLeft();
            } else {
                moveRight();
            }
            return true;
        }
    }

    private void moveRight() {
        if (hs.getScrollX() > 0 && hs.getScrollX() < mWidth * cN)
        {
            hs.smoothScrollBy(mWidth * cN - hs.getScrollX(), 0);
            cN++;
        }
        //Log.v("cN", Integer.toString(cN));
    }

    private void moveLeft() {

        if (hs.getScrollX() > 0 && hs.getScrollX() < mWidth)
        {
            hs.smoothScrollBy( -hs.getScrollX(), 0);
            cN = 1;
        }
        else if (hs.getScrollX() > mWidth && hs.getScrollX() < mWidth * (cN - 1) )
        {
            hs.smoothScrollBy(mWidth * (cN - 2) - hs.getScrollX(), 0);
            cN--;
        }
        //Log.v("cN", Integer.toString(cN));
    }