How to get the current Y offset of a ScrollView

后端 未结 5 1784
我寻月下人不归
我寻月下人不归 2020-12-04 23:46

ScrollView has a method for setting the x and y scroll offset, but no method for getting the current offset (all I\'m really interested is the y offset, since ScrollView onl

相关标签:
5条回答
  • 2020-12-05 00:08

    Call getScrollY() on the ScrollView

    See here for the documentation: http://developer.android.com/reference/android/view/View.html#getScrollY%28%29

    0 讨论(0)
  • 2020-12-05 00:12

    I achieve to get by the following. First get screen heigh and width.

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    float screenWidth = metrics.widthPixels;
    float screenHeight = metrics.heightPixels;
    

    then to find out the document height (the total, what is being shown and what is out of the screen)

    public float getDocumentHeight(){
        return (computeVerticalScrollRange() * screenHeight)/computeVerticalScrollExtent();
    }
    

    Finally to get the offset

    public float getTopY(){
        return (getDocumentHeight() * computeVerticalScrollOffset())/computeVerticalScrollRange();
    }
    

    This give you the top of the window relative to the part of the document you are seeing so you could find the exact position of an event by

    public boolean onTouchEvent(MotionEvent event) {
          int y = event.getY() + (int) getTopY();
        }
    

    You can also do something similar to handle the width

    0 讨论(0)
  • 2020-12-05 00:13

    Why don't you try something like this ?

    targetScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                int scrollX = targetScrollView.getScrollX();
                Log.d(TAG, "scrollX: " + scrollX);
            }
        });
    
    0 讨论(0)
  • 2020-12-05 00:21

    What about: computeHorizontalScrollOffset() and computeVerticalScrollOffset().

    0 讨论(0)
  • 2020-12-05 00:30

    If you are certain that you should get some value after using getScrollY() or getTop(), try to put those method inside a

    yourScroolView.post(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getApplicationContext(),"Current Y is : "+getScrollY,Toast.LENGTH_SHORT).show();
                }
            });
    

    Now it should work. According to my understanding about this method, it will only run after the layout being drawn. That can be one of the reason why you kept getting 0 previously. Hope it helps.

    0 讨论(0)
提交回复
热议问题