在滚动视图中获取滚动方向?

时间:2011-09-20 19:04:04

标签: android

这应该非常简单,但似乎我错过了一些东西---你如何计算ScrollView的滚动事件的方向(左/右/上/下)?

首先想到的是存储getScrollX()和getScrollY(),然后在下一次调用onTouchListener时对它们进行比较。这是正确的做事方式吗?

我正在实现自定义Horizo​​ntalScrollView,我只需要在一个方向上禁用滚动和页面滑动。

2 个答案:

答案 0 :(得分:8)

研究告诉我,那个案子没有卷轴监听器 你可以试试你的approch 我要尝试的另一件事是覆盖onScrollChanged(之前提供滚动位置),因此创建自己的ScrollView

<强>更新
这个适合我。它向右滚动但不向左滚动。

public class CustomScrollView extends HorizontalScrollView {

    public CustomScrollView(Context context) {
        super(context);
    }

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onScrollChanged(int w, int h, int ow, int oh) {
        if (w < ow) {
            scrollTo(ow, h);
        }
    }
}

答案 1 :(得分:2)

使用此

  scrollView.setOnTouchListener(new View.OnTouchListener() {
  float y1 = 0;
  float y0 = 0;

  @Override
  public boolean onTouch(View view, MotionEvent motionEvent) {

    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
      y0 = motionEvent.getY();
      Log.i("Y", motionEvent.getAction() + " + " + (y0 - y1));
    } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
      y1 = motionEvent.getY();
      if (y0 - y1 > 0) {
        Log.i("Y", motionEvent.getAction() + " + " + (y0 - y1));
      } else if (y0 - y1 < 0) {
        Log.e("Y", motionEvent.getAction() + " - " + (y0 - y1));
      }
    }

    return false;
  }
});
相关问题