Android: get scroll position of webview

I am new to Android.

I would just like to know where the user scrolls on the page. When a certain point appears on the web page at the bottom of the screen, I want to trigger an event. But this code throws an exception. I know that WebView inherits getScrollY () from the view. I do not implement 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;
    }
}
+5
source share
4 answers

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

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

You write WebView webview;in two places inside the OnCreate () method.

Just write webview = new WebView(this);insteadWebView webview = new WebView(this);

This way you can solve the null pointer problem.

+2

WebView , :

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");
        }
    }
}

:

  • WebView,
  • , scrollY
  • Nexus 5X Android 8 , 1dp ( )
0

, Ionic Framework.

scrollTop Webview & lt; ion-content id = "_ ionic_content"> , ion_content .

-, :

JavaScript ->

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

.

0

Source: https://habr.com/ru/post/1737197/


All Articles