Android: Get the scroll position of a WebView

android, webview

Solution

The WebView has a method to get its content height, which I used in my solution:

webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
    @Override
    public void onScrollChange(View view, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        WebView webView = (WebView) view;
        float contentHeight = webView.getContentHeight() * webView.getScaleY();
        float total = contentHeight * getResources().getDisplayMetrics().density - view.getHeight();
        // on some devices just 1dp was missing to the bottom when scroll stopped, so we subtract it to reach 1
        float percent = Math.min(scrollY / (total - getResources().getDisplayMetrics().density), 1);
        Log.d("SCROLL", "Percentage: " + percent);
        if (scrollY >= total - 1) { 
                        Log.d("SCROLL", "Reached bottom");
        }
    }
}

Look out for:

- WebView scale has to be taken into account to get the total scroll height

- Display density has to be multiplied into content height to compare it with scrollY

- On my Nexus 5X on Android 8 the scrollY never reached the height, but stopped 1dp before the end (workaround is included in code)

Problem

I'm new to Android. I would like to simply know where on a page the user has scrolled. When a certain point on the web page appears at the bottom of the screen, I want to trigger an event. But this code causes an exception. I know that WebView inherits `getScrollY()` from View. Am I not implementing it correctly? Thanks in advance. ``` public class Scroll extends Activity { public WebView webview; public float yPos; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webview = new WebView(this); setContentView(webview); webview.loadUrl("file:///android_asset/Scroll.html"); } public boolean onTouchEvent(final MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE) { yPos = webview.getScrollY(); Log.v("Scroll", "yPos = " + yPos); } return false; } } ```

Original source