2011-03-23 113 views
3

我想做一个Horizo​​ntalScrollView分页。如果您将屏幕移动到右侧,则会显示正确的“页面”,如果将屏幕移动到左侧,则会显示左侧的“页面”。Horizo​​ntalScrollView分页

+1

尝试使用具有项目宽度的图库作为页面宽度。 – Karan 2011-03-23 15:07:33

回答

12

我已经做过这件事了。你可以通过一个自定义的触摸监听器来做到这一点:

public MyHorizontalScrollView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    setOnTouchListener(new View.OnTouchListener() { 
      public boolean onTouch(View v, MotionEvent event) { 
       if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL){ 
        int scrollX = getScrollX(); 
        int itemWidth = getMeasuredWidth(); 
        int activeItem = ((scrollX + itemWidth/2)/itemWidth); 
        int scrollTo = activeItem * itemWidth; 
        smoothScrollTo(scrollTo, 0); 

        return true; 
       } else { 
        return false; 
       } 
      } 
     }); 
    } 

我觉得很不言自明。这假设你的页面宽度是恒定的并且等于整个滚动视图的宽度。

相关问题