Skip to content Skip to sidebar Skip to footer

Android: Get The Scroll Position Of A Webview

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 a

Solution 1:

And the exception is? Here is a note on WebView screen heights from one of my apps:

// current position (top) = getScrollY();  // max position = getContentHeight();  // screen height = getHeight();

Solution 2:

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

webView.setOnScrollChangeListener(newView.OnScrollChangeListener() {
    @OverridepublicvoidonScrollChange(View view, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        WebViewwebView= (WebView) view;
        floatcontentHeight= webView.getContentHeight() * webView.getScaleY();
        floattotal= 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 1floatpercent= 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)

Solution 3:

You are writing WebView webview; at two places inside the OnCreate() method.

Simply write webview = new WebView(this); instead of WebView webview = new WebView(this);

This way you can solved the null pointer issue.

Solution 4:

This worked for me, I am calculating the basic scrolling position.

mainWebView.setOnScrollChangeListener { view, scrollX, scrollY, oldScrollX, oldScrollY ->

        if (scrollY > 800) {
            supportActionBar!!.setDisplayHomeAsUpEnabled(true)
            toolbar.logo = resources.getDrawable(R.mipmap.ic_launcher)
        } else {
            supportActionBar!!.setDisplayHomeAsUpEnabled(false)
            toolbar.logo = null
        }
        Log.e(TAG, "initializeWeb: $scrollY")
    }

Solution 5:

For those who are using Ionic framework.

Getting the scrollTop from the Webview < ion-content id="_ionic_content" > does not work, because ion_content wraps it's own scroller.

To get the scrollTop of the webView use :

javascript ->

var scroller = $('#_ionic_content')[0].firstChild.offsetParent;
 var  scrollTop_pos = scroller.scrollTop;

This has worked for me.

Post a Comment for "Android: Get The Scroll Position Of A Webview"